Exception Handling
1. An Exception is an abnormal condition that is caused during
execution (run-time environment) of a program.
2. When the java interpreter encounters an error, such as dividing an
integer by zero, it creates an exception object and throws it. (i.e.
displays message that error has occurred)
3. When there is run time error, the JVM generates Exception Object. The
generated object needs to be caught. If not caught, then it stops flow of
execution of a program.
4. Java handles exception using five keywords try, catch, finally, throws
and throw.
5. If the exception is not caught and handled properly, interprets will
display an error message and will terminate the program causing to fail or
crash.
6. If we want to continue with execution of remaining code, then we should
try to catch the exception object thrown by the error condition and then
display an appropriate message for corrective action. This task is known
as Exception Handling.
7. The main subclass of Exception class is the Runtime Exception Class. For
example, try to access of invalid array index, division by zero, etc.
cannot be known at compilation time, generated at runtime.
Object class & Its Subclasses for Exception
One of the subclasses of Object class is throwable.
Two types of exceptions:
Checked Exceptions: Exceptions that are checked during the compilation process
are called as checked exceptions. A checked exception is an exception that is typically a user
error or a problem that cannot be foreseen by the programmer.
Unchecked Exceptions:
Exceptions which are thrown during Runtime by java interpreter are known
as unchecked exceptions. Exceptions generated from runtime are called unchecked exceptions, since it is not possible for the compiler to determine that
your code will handle the exception. Exception classes that descend from Runtime Exception and Error classes are unchecked exceptions. Examples for Runtime Exception are illegal cast operation, inappropriate use of a null pointer,
referencing an out of bounds array element. Error exception classes signal
critical problem that typically cannot be handled by your application.
Examples are out of memory error, stack overflow, failure of the java
VM.
Thrown exceptions are referred to as checked exceptions. The
compiler will confirm at compile time that the method includes code that
might throw an exception. Moreover the compiler requires the code that calls
such a method to include this call within a try block, and provide an
appropriate catch block to catch the exception.
When an (either checked or unchecked) exception is thrown execution will
attempt to immediately branch to the first block whose associated exception
class matches the class or the thrown exception is not caught in a matching
catch block, execution of the method immediately terminates and
control returns to the invoker of the method, where this process is
repeated. The result is that the exception chain is escalated until a
matching catch block is found. If not, the thread containing
the thrown exception is terminated.
Exceptions :
Throwable class has two useful methods:
void printStackTrace()
Prints the Throwable and the Throwable’s stack trace. This is what you’ve
seen printed on the console when an exception is thrown but not caught, causing non-GUI programs to
stop.
String getMessage()
Gets the detail message string of the Throwable
public void f()
{
new Throwable(" In X.f ").printStackTrace();
}
Mechanism of Exception Handling
1) Find the problem (Hit exception)
2) Inform that error has occurred (Throw the exception)
3) Receive the error (catch the exception)
4) Take corrective actions (handle the exception)
try-catch Block
Program statements which need to be monitor /checked for exception are
included in try block. If the exception occurs within the try block. Then
java runtime system creates an exception objects and throw it and catch
block tries to match exception object thrown by try block with Exception
Type mentioned in the catch block.
Syntax
try
{
/* block of code to checking errors
(Generates an Exception)*/
}
catch (ExceptionType ExceptionObject)
{
/* Exception handler for Exception Type (process
the exception) */
}
If it matches then exception is caught by catch block. Otherwise, default
handler will terminate the program by displaying message. We should take
corrective mechanism in catch block. The catch block cannot be separated
from the try block. Once the errors object is generated within the try
block, the remaining statement will not be executed. Instead control is
transferred to catch block. Every try statement should have at least one
catch statement, otherwise compiles reports errors.
Program : try and catch to handle arithmetic exception
Code
class ExceptionDemo { public static void main(String args[]) { int a = 10, b = 5, c = 5; int x, y; try { x = a/(b-c); } catch(ArithmeticException e) { System.out.prntin("Division by zero"); } y = a / (b + c); System.out.printin("y="+y); } }
Output:
Division by zero
y=1
Multiple Catch Statements
When an exception in a try block is generated, java treats the multiple
catch statements like cases in switch statement, The first statement whose
parameter matches with the exception object will be executed, and the
remaining statement will be skipped.
Syntax:
try
{
/*block of code to checking errors (Generates an
Exception)*/
}
catch(Exceptiontype1 exceptionobject)
{
//processes the exception of type
ExceptiontypeN
}
catch(Exceptiontype2 exceptionobject)
{
//processes the exception of type
Exceptiotype2
}
|
|
catch(ExceptiontypeN exceptionobject)
{
//processes the exception of type
ExceptiontypeN
}
Program
Code
class MultipleHandleDemo { public static void main(String args[]) { int a[ ] = {5,10}; int b =5; try { b = b/(a[0]-a[1]); } catch(ArithmeticException e) { System.out.println("Division by zero"); } catch(ArrayIndexOutOfBoundException e) { System.out.println("Array index error"); } catch(ArrayStoreException e) { System.out.println("Wrong data type"); } int y = a [1] – a [0]; System.out.println("y="+y); } }
finally block
The finally block is used to display the information or to execute the statements, which needs to be executed irrespective of the catch block. This means that the finally block must be executed in spite of the fact that a catch block is executed or not. Some rules for using the finally block are as follows.
A finally block must be declared at the end of the last catch block. if finally block is declared before a catch block, then program will not compile successfully. Multiple finally blocks cannot be used with the try block. Doing so generates a compile time error starting that a finally block cannot be used without a try block, even though we have used the try block in the program. Java Application may use the resources of database system, files, operating system. After the use of these resources, java must free those resources. Code to free the resources is written inside the finally Block. Garbage collector can be also called through finally Block.
Throwing our own Exception (Managing user defined Exception Handling)
There may be situation where we would like to throw our own Exception (user defined Exception). We can do that by using 'throw' clause. When you discover an error you can't handle locally, it's time to use the exception mechanism.
When throw statement is executed, it stops execution of current method and generates the exception object.
The syntax for the throw statement is:
throw new NameOfExceptionClass();
Ex. throw new NumberFormatException();
'throws' clause
This keyword is used in Java to throw the exception objects from the called method to the calling method. It works similar to return statement. If a method generates an exception and does not handle the exception by catch block, then the programmer must specify the keyword throws so that the caller of the method can guard its code against that exception. If a method generates a checked exception and the programmer does not want to handle this exception, then he should throw it out by using the keyword throws, otherwise an error would be flagged by Java compiler. However, in the case of unchecked exception, if the programmer does not want to handle the exception, then he should not throw it out by using the keyword throws. -\ Exception handling provides two benefits. These are :(a) allows fixing the bug. (b) prevents automatic termination of the program.
Syntax to use 'throw' and 'throws' clause
returntype methodname(parameter list) throws NameOfExceptionclass
{
if(condition)
{
throw new NameOfExceptionclass();
}
}
Program:
Code
class MyException extends Exception { MyException(String message) { Super(message); } } class TestMyException { public static void main(String args[]) { int x = 5, y = 1000; try { float z = (float) x / (float) y; if(z <0.01) { throw new MyException("Number is too small"); } } catch(MyException e) { System.out.println("Caught my exception"); System.out.println(e.getMessage); } finally { System.out.println("I am always here"); } } }
Output:
Caught my exception
Number is too small
I am always there
Difference between throw and throws?
Difference between checked Exception and un-checked Exception?
Post a Comment