Java Exceptions
Java Exceptions
Exceptions in Java represent errors that occur during execution of a program.
Exception handling is used to avoid undesirable display errors, but also easier to correct any errors.
To handle exceptions occurred during runtime uses:
The try-catch-finally
Exception thrown by method throws
Exception example
Try-catch-finally example
public class ExceptionExample{ public static void main(String [] args){ try{ System.out.println("Start"); int a = Integer.parseInt("123abc"); }catch(NumberFormatException ex1){ ex1.printStackTrace(); System.out.println("Is not numeric!"); }catch(Exception ex2){ ex2.printStackTrace(); }finally{ System.out.println("End"); } } }
Throws example
class Exception1 extends Exception { public Exception1() {} } public class TestException { public static void m1() throws Exception1 { int a=5; if(a>7){ System.out.println("OK"); }else{ System.out.println("Exception a="+a); throw new Exception1(); } } public static void main(String[] args) { try { m1(); } catch(Exception1 e){ e.printStackTrace(); } } }