Tuesday, July 22, 2008

JAVA-EXCEPTION HANDLING

EXCEPTION HANDLING

1). What is Exception?

An exception is an abnormal condition that arises on programming code at run time. An exception is a run time error.

2). What is java Exception?

A java Exception is an object that describes an exceptional condition that has occurred in a piece of code. When an exceptional condition arises, an object representing that exception is created and thrown to the method that caused error. That method may choose to handle the exception itself or pass to on.

3). How many ways the java exception occurred?

There are two ways.

1). Java run-time system. 2). Manually generated by programming code.

4). What does java run-time system exception means?

Exception thrown by java relate to fundamental errors that violate the rules of the java language. Java run-time system exception are automatically thrown by the java run-time system.

5). What does manually generated exception?

Manually generated exceptions are used to report some error condition to the caller of a method. To manually throw an exception, use keyword throw.

6). How does java exception managed or handled?

Java exception handling is managed via five keywords: try, catch, and throw, throws, finally.

7). How does exception handling work?

Program statements that monitor for exception are contained within a try block. If an exception occurs within the try block, it is thrown. The catch clause can catch this exception and handle the exception.

Note: all exception types are subclasses of built-in class Throwable.

8). What is uncaught exception?

Any exception is not caught by program will be processed by the default handler. The default handler displays a string that describes the exception, print stack trace and terminates the program.

9) What is stack trace?

The stack trace will show the sequence of method invocation that led up to the error.

10) Although java run-time systems handle exception, why we use try and catch?

Two benefits:

1). It allows to fix error. 2). It prevents the program from automatically terminating.

11). Why we use multiple catch clauses for single statement?

In some cases, more than one exception can be raised by a single piece of code. To handle this type of exception, you can specify two or more catch clauses, each catch have different type of exception. When an exception is thrown, each catch statement is inspected in order and the first one whose type matches that of the exception is executed. After one catch statement excutes, the others are bypassed, and execution continues after the try/catch block.

12). What is nested try statement?

The try statement can be nested. A try statement can be inside the block of another try. Each time a try statement is entered, the context of that exception is pushed on the stack. If an inner try statement does not have a catch handler for a particular exception, the stack is unwound and the next try statement’s catch handlers are inspected for a match. This continues until one of the catch statements succeeds, or the java run-time system will handle the exception.

13). What is throwing an Exception?.

The act of passing an Exception Object to the runtime system is called Throwing an Exception.

14) What is the use of throw statement?

It is possible to throw an exception explicitly using throw statement.

15) What is the use of throws statement?

If a method is capable of causing an exception that it does not handle, it must specify this behavior so that the callers of the method can guard themselves against that exception. We do this by using throws clause in method’s declaration. The throws clause lists the types of exceptions that a method might throw. This is necessary for all exception except the type Error or Runtime Exception or their subclasses. All exception that a method can throw must be declared in the throws clause. If they are not, the compile time error will result.

16). What is the unchecked exception?

An unchecked exception need not be included in any method’s throws list. Because the compiler dose not check if a method handles or throws these exceptions.

17). What is the checked exception?

A checked exception included in method’s declaration if the method can generated one of these exceptions and does not handle it itself.

18). What is chained exception?

The chained exception features allow to associate another exception with an exception. The second exception describes the cause of the first exception.

19) What is NullPointerException and how to handle it?

When an object is not initialized, the default value is null. When the following things happen, the NullPointerException is thrown:
--Calling the instance method of a null object.
--Accessing or modifying the field of a null object.
--Taking the length of a null as if it were an array.
--Accessing or modifying the slots of null as if it were an array.
--Throwing null as if it were a Throwable value.
The NullPointerException is a runtime exception. The best practice is to catch such exception even if it is not required by language design.

20). What is the purpose of the finally clause of a try-catch-finally statement?

The finally clause is used to provide the capability to execute code no matter whether or not an exception is thrown or caught.

21) What classes of exceptions may be caught by a catch clause?
A catch clause can catch any exception that may be assigned to the Throwable type. This includes the Error and Exception types.

22) What is the difference between throw and throws keywords?
The throw keyword denotes a statement that causes an exception to be initiated. It takes the Exception object to be thrown as argument. The exception will be caught by an immediately encompassing try-catch construction or propagated further up the calling hierarchy.
The throws keyword is a modifier of a method that designates that exceptions may come out of the method, either by virtue of the method throwing the exception itself or because it fails to catch such exceptions that a method it calls may throw.

23) Does the code in finally block get executed if there is an exception and a return statement in a catch block?
If an exception occurs and there is a return statement in catch block, the finally block is still executed. The finally block will not be executed when the System.exit(1) statement is executed earlier or the system shut down earlier or the memory is used up earlier before the thread goes to finally block.

24)When is the ArrayStoreException thrown?
When copying elements between different arrays, if the source or destination arguments are not arrays or their types are not compatible, an ArrayStoreException will be thrown.

25) WHEN IS THE ArithmeticException thrown?
The ArithmeticException is thrown when integer is divided by zero or taking the remainder of a number by zero. It is never thrown in floating-point operations.

26)What is the catch or declare rule for method declarations?
If a checked exception may be thrown within the body of a method, the method must either catch the exception or declare it in its throws clause.

27)Can an exception be rethrown?
Yes, an exception can be rethrown.

28)What happens if an exception is not caught?
An uncaught exception results in the uncaughtException() method of the thread's ThreadGroup being invoked, which eventually results in the termination of the program in which it is thrown.

29)Which arithmetic operations can result in the throwing of an ArithmeticException?
Integer / and % can result in the throwing of an ArithmeticException.

30)What happens if a try-catch-finally statement does not have a catch clause to handle an exception that is thrown within the body of the try statement?
The exception propagates up to the next higher level try-catch statement (if any) or results in the program's termination.

31)What happens if an exception is not caught?
An uncaught exception results in the uncaughtException() method of the thread's ThreadGroup being invoked, which eventually results in the termination of the program in which it is thrown.

32)How does a try statement determine which catch clause should be used to handle an exception?
When an exception is thrown within the body of a try statement, the catch clauses of the try statement are examined in the order in which they appear. The first catch clause that is capable of handling the exception is executed. The remaining catch clauses are ignored.

33) Explain the user defined Exceptions?


User defined Exceptions are the separate Exception classes defined by the user for specific purposed. An user defined can create by simply sub-classing it to the Exception class. This allows custom exceptions to be generated (using throw) and caught in the same way as normal exceptions.
Example:
class myCustomException extends Exception {
// The class simply has to exist to be an exception
}

34) What are checked exceptions?


Checked exceptions are those that the Java compiler forces you to catch. e.g. IOException are checked Exceptions.

----------------------------------------------------------------------------------------------------------------------

35) What are runtime exceptions?


Runtime exceptions are those exceptions that are thrown at runtime because of either wrong input data or because of wrong business logic etc. These are not checked by the compiler at compile time.

36) What is the difference between error and an exception?

An error is an irrecoverable condition occurring at runtime. Such as OutOfMemory error. These JVM errors and you can not repair them at runtime. While exceptions are conditions that occur because of bad input etc. e.g. FileNotFoundException will be thrown if the specified file does not exist. Or a NullPointerException will take place if you try using a null reference. In most of the cases it is possible to recover from an exception (probably by giving user a feedback for entering proper values etc.).

37) How to create custom exceptions?


Your class should extend class Exception.

38) If I want an object of my class to be thrown as an exception object, what should I do?


The class should extend from Exception class. Or you can extend your class from some more precise exception type also.

39) If my class already extends from some other class what should I do if I want an instance of my class to be thrown as an exception object?


One cannot do anything in this scenario. Because Java does not allow multiple inheritance and does not provide any exception interface as well.

---------------------------------------------------------------------------------------------------------

40). How does an exception permeate through the code?


An unhandled exception moves up the method stack in search of a matching When an exception is thrown from a code which is wrapped in a try block followed by one or more catch blocks, a search is made for matching catch block. If a matching type is found then that block will be invoked. If a matching type is not found then the exception moves up the method stack and reaches the caller method. Same procedure is repeated if the caller method is included in a try catch block. This process continues until a catch block handling the appropriate type of exception is found. If it does not find such a block then finally the program terminates.

----------------------------------------------------------------------------------------------------------

41) What are the different ways to handle exceptions?


There are two ways to handle exceptions,
1. By wrapping the desired code in a try block followed by a catch block to catch the exceptions. and
2. List the desired exceptions in the throws clause of the method and let the caller of the method handle those exceptions.

42) What is the basic difference between the 2 approaches to exception handling.
1. Try catch block and
2. Specifying the candidate exceptions in the throws clause?
When should you use which approach?
In the first approach as a programmer of the method, you yourself are dealing with the exception. This is fine if you are in a best position to decide should be done in case of an exception. Whereas if it is not the responsibility of the method to deal with it's own exceptions, then do not use this approach. In this case use the second approach. In the second approach we are forcing the caller of the method to catch the exceptions, that the method is likely to throw. This is often the approach library creators use. They list the exception in the throws clause and we must catch them. You will find the same approach throughout the java libraries we use.

43) Is it necessary that a catch block must follow each try block?


It is not necessary that a catch block must follow each try block. It should be followed by either a catch block OR a finally block. And whatever exceptions are likely to be thrown should be declared in the throws clause of the method.

--------------------------------------------------------------------------------

44) If I write return at the end of the try block, will the finally block still execute?


Yes even if you write return as the last statement in the try block and no exception occurs, the finally block will execute. The finally block will execute and then the control return.

45) If I write System.exit (0); at the end of the try block, will the finally block still execute?


No in this case the finally block will not execute because when you say System.exit (0); the control immediately goes out of the program, and thus finally never executes.

46) How does a try statement determine which catch clause should be used to handle an exception?


When an exception is thrown within the body of a try statement, the catch clauses of the try statement are examined in the order in which they appear. The first catch clause that is capable of handling the exceptionis executed. The remaining catch clauses are ignored.

--------------------------------------------------------------------------------

47) What is the catch or declare rule for method declarations?


If a checked exception may be thrown within the body of a method, the method must either catch the exception or declare it in its throws clause.

48) Which package contains exception handling related classes?
java.lang
------------------------------------------------------------------------------------------------------------

49) What are the two types of Exceptions?


Checked Exceptions and Unchecked Exceptions.
------------------------------------------------------------------------------------------------------------


50) What is the base class of all exceptions?
java.lang.Throwable
------------------------------------------------------------------------------------------------------------


51) What is the difference between Exception and Error in java?
Exception and Error are the subclasses of the Throwable class. Exception class is used for exceptional conditions that user program should catch. Error defines exceptions that are not excepted to be caught by the user program. Example is Stack Overflow.

------------------------------------------------------------------------------------------------------------

52) What is the difference between throw and throws?
throw is used to explicitly raise a exception within the program, the statement would be throw new Exception(); throws clause is used to indicate the exceptions that are not handled by the method. It must specify this behavior so the callers of the method can guard against the exceptions. throws is specified in the method signature. If multiple exceptions are not handled, then they are separated by a comma. the statement would be as follows: public void doSomething() throws IOException,MyException{}
------------------------------------------------------------------------------------------------------------


53) Differentiate between Checked Exceptions and Unchecked Exceptions?
Checked Exceptions are those exceptions which should be explicitly handled by the calling method. Unhandled checked exceptions results in compilation error.

Unchecked Exceptions are those which occur at runtime and need not be explicitly handled. RuntimeException and it's subclasses, Error and it's subclasses fall under unchecked exceptions.
------------------------------------------------------------------------------------------------------------


54) What are User defined Exceptions?
Apart from the exceptions already defined in Java package libraries, user can define his own exception classes by extending Exception class.
------------------------------------------------------------------------------------------------------------

55) What is the importance of finally block in exception handling?
Finally block will be executed whether or not an exception is thrown. If an exception is thrown, the finally block will execute even if no catch statement match the exception. Any time a method is about to return to the caller from inside try/catch block, via an uncaught exception or an explicit return statement, the finally block will be executed. Finally is used to free up resources like database connections, IO handles, etc.
------------------------------------------------------------------------------------------------------------


56) Can a catch block exist without a try block?
No. A catch block should always go with a try block.
------------------------------------------------------------------------------------------------------------


57) Can a finally block exist with a try block but without a catch?
Yes. The following are the combinations try/catch or try/catch/finally or try/finally.
------------------------------------------------------------------------------------------------------------


58) What will happen to the Exception object after exception handling?
Exception object will be garbage collected.
------------------------------------------------------------------------------------------------------------


59) The subclass exception should precede the base class exception when used within the catch clause. True/False?
True.
------------------------------------------------------------------------------------------------------------


60) Exceptions can be caught or rethrown to a calling method. True/False?
True.
------------------------------------------------------------------------------------------------------------


61) The statements following the throw keyword in a program are not executed. True/False?
True.
------------------------------------------------------------------------------------------------------------


62) How does finally block differ from finalize() method?
Finally block will be executed whether or not an exception is thrown. So it is used to free resoources. finalize() is a protected method in the Object class which is called by the JVM just before an object is garbage collected.
------------------------------------------------------------------------------------------------------------


63) What are the constraints imposed by overriding on exception handling?
An overriding method in a subclass may only throw exceptions declared in the parent class or children of the exceptions declared in the parent class.
------------------------------------------------------------------------------------------------------------

64). If we don’t use exception handling what will happen?

If we don’t use exception handling, the exception is caught by the default handler provided by java run-time system.

65). What are the types of error?

There are two type of error.

1). Compile-time error.

2). Run-time error.

------------------------------------------------------------------------------------------------------------

66). What is compile time error?

All syntax error will be detected and displayed by java compiler. So they are compile time error.

If the compiler display error, it will not create .class file.

------------------------------------------------------------------------------------------------------------

67). What is run time error?

The program may compile successfully and create .class file but may not run properly. Such a program may produce wrong result or terminate program. Exam is stack overflow.

------------------------------------------------------------------------------------------------------------

No comments: