Exception Handling in Java
Exception Handling in Java
Exception
Introduction
An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions. A Java exception is an object that describes an exceptional (that is, error) condition that has occurred in a piece of code. An exception is an abnormal condition that arises in a code sequence at run time. In other words, an exception is a run-time error.
Exception Handling
class Exception { public static void main (String arr[]) { System.out.println(Enter two numbers); Scanner s = new Scanner (System.in); int x = s.nextInt(); int y = s.nextInt(); int z = x/y; System.out.println(result of division is : + z); } }
Exception Handling
An Exception is a run-time error that can be handled programmatically in the application and does not result in abnormal program termination. Exception handling is a mechanism that facilitates programmatic handling of run-time errors. In java, each run-time error is represented by an object.
RuntimeException is the sub-class of Exception. Exceptions of this type are automatically defined for the programs that we write and include things such as division by zero and invalid array indexing. Each exception is a run-time error but all run-time errors are not exceptions.
Throwable
Exception Run-time Exception - ArithmeticException - ArrayIndexOutOf BoundsException - NullPointerException Error - VirtualMachine - NoSuchMethod - StackOverFlow
IOEXception SQLException
Checked Exception
Unchecked Exception
Checked Exception
Checked Exceptions are those, that have to be either caught or declared to be thrown in the method in which they are raised. It is a reminder by compiler to programmer to handle failure senarios. When to use:
Operation where chances of failure are more eg: IO operation, database access, networking operation, etc.
Unchecked Exception
Those exceptions whose handling is not verified during compile-time. It is direct sub-class of RuntimeException. Advantage: maintains code readability. They arise due to:
Programming errors (like accessing method of null object, accessing element outside array)
ArrayIndexOutOfBoundsException
NumberFormatException NullPointerException IOException
StackOverFlowError
NoClassDefFoundError NoSuchMethodError
Uncaught Exceptions
class Exception_Demo { public static void main(String args[]) { int d = 0; int a = 42 / d; } } When the Java run-time system detects the attempt to divide by zero, it constructs a new exception object and then throws this exception. once an exception has been thrown, it must be caught by an exception handler and dealt with immediately.
In the previous example, we havent supplied any exception handlers of our own. So the exception is caught by the default handler provided by the Java run-time system. Any exception that is not caught by your program will ultimately be processed by the default handler. The default handler displays a string describing the exception, prints a stack trace from the point at which the exception occurred, and terminates the program. java.lang.ArithmeticException: / by zero at Exc0.main(Exc0.java:4)
Exception Handling
try
used to execute the statements whose execution may result in an exception. try {
Note: try block is always used either with catch or finally or with both.
catch
catch is used to define a handler. It contains statements that are to be executed when the exception represented by the catch block is generated. If program executes normally, then the statements of catch block will not executed. If no catch block is found in program, exception is caught by JVM and program is terminated.
class Divide{ public static void main(String arr[]){ try { int a= Integer.parseInt(arr[0]); int b= Integer.parseInt(arr[1]); int c = a/b; System.out.println(Result is: +c); } catch (ArithmeticException e) {System.out.println(Second number must be non-zero);} catch (NumberFormatException n) {System.out.println(Arguments must be Numeric);}
Nested Trys
class NestedTryDemo { public static void main(String args[]){ try { int a = Integer.parseInt(args[0]); try { int b = Integer.parseInt(args[1]); System.out.println(a/b); } catch (ArithmeticException e) { System.out.println(Div by zero error!"); } } catch (ArrayIndexOutOfBoundsException) { System.out.println(Need 2 parameters!"); } }}
class Divide{ public static void main(String arr[]){ try { int a= Integer.parseInt(arr[0]); int b= Integer.parseInt(arr[1]); int c = a/b; System.out.println(Result is: +c); } catch (Throwable e) { System.out.println(e); } } }
throw
used for explicit exception throwing. throw(Exception obj); throw keyword can be used: to throw user defined exception to customize the message to be displayed by predefined exceptions to re-throw a caught exception
class ThrowDemo { static void demo() { try { throw new NullPointerException("demo"); } catch(NullPointerException e) { System.out.println("Caught inside demo."); throw e; // rethrow the exception } } public static void main(String args[]) { try { demo(); } catch(NullPointerException e) { System.out.println("Recaught: " + e); } } }
All other exceptions that a method can throw must be declared in the throws clause. If they are not, a compile-time error will result.
import java.io.*; public class ThrowsDemo { public static void main( String args []) throws IOException { char i; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter character, 'q' to quit"); do{ i = (char) br.read(); System.out.print(i); }while(i!='q'); } }
Finally
finally creates a block of code that will be executed after a try/catch block has completed and before the code following the try/catch block. The finally block will execute whether or not an exception is thrown.
If an exception is thrown, the finally block will execute even if no catch statement matches the exception.
If a finally block is associated with a try, the finally block will be executed upon conclusion of the try. The finally clause is optional. However, each try statement requires at least one catch or a finally clause.
class Myexception extends Throwable { public Myexception(int i) { System.out.println("you have entered ." +i +" : It exceeding the limit"); } }
public class ExceptionTest { public void show(int i) throws Myexception { if(i>100) throw new Myexception(i); else System.out.println(+i+" is less then 100 it is ok"); } public static void main(String []args){ int i=Integer.parseInt(args[0]); int j=Integer.parseInt(args[1]); ExceptionTest t=new ExceptionTest(); try{ t.show(i); t.show(j); } catch(Throwable e) { System.out.println("catched exception is "+e); } } }