1)Try
2)Catch
3)Finally
4)Throw
5)Throws
try { } catch(Exception e)//throwable type { }
Exception Handling in Java, If there is no exception in try block, catch block will not be executed. For a try block, multiple catch blocks can be written. Inside try and catch block, there is a chance to write try block again. While developing try-catch block if we define multiple catch block then the catch block which is declared with super most type must be always written at the end. When it is unknown which exception will occur, then Throwable class can be used. Following is the syntax.
try { } catch(ArithmeticException e1)//throwable type { } catch(Exception e2)//throwable type { try { <code>} catch(Throwable e)//throwable type {</code> } }
Only one catch gets executed which corresponds to the execution occurred.
try { } catch(Exception e)//throwable type { } finally { System.out.println("Mandatory statements"); }
package com.spl.exception; public class Exception1 { public static void main(String[] args) { System.out.println("Program starts"); int k; int i=10; int j=0; int[] array=new int[2]; System.out.println("i value="+i); System.out.println("j value="+j); try { k=i/j; } catch(ArithmeticException e) { e.printStackTrace(); } try { array[3]=456; //System.exit(0); } catch(ArrayIndexOutOfBoundsException e) { e.printStackTrace(); } finally { System.out.println("Running finally"); } System.out.println("i value="+i); System.out.println("j value="+j); System.out.println("Program ends"); } }
Output:
When compile the code result will be as follows.
Unchecked Exception: Any exception if compiler is unable to identify at the time of compilation then it is known as unchecked exception. Unchecked exceptions are handled using try-catch block.
All exceptions classes inheriting Exception class, except RuntimeException are known as checked exception. Rest all are unchecked exceptions.
Generally the exception objects are created and thrown by JVM, programmer can also create an exception object and throw it.
For more detailed information on method click here .
throw new ArithmeticException();
package com.spl.exception; public class Exception2 { public static void main(String[] args){ System.out.println("Program starts"); try { demo(); } catch(ClassNotFoundException e) { System.out.println("Exception handled"); e.printStackTrace(); } System.out.println("Program ends"); } static void demo() throws ClassNotFoundException { Class.forName("com.spl.demo"); } }
Output:
When compile the code result will be as follows.
package com.spl.exception; public class Exception3 { public static void main(String[] args){ System.out.println("Program starts"); demo(12); System.out.println("Program ends"); } static void demo(int i) { if(i<15) { throw new ArithmeticException("i<15"); } } }
Output:
When compile the code result will be as follows.