Syntax:
try{ } catch(Exception e){ }
/** * @author lautturi.com * Java example:catch exception in java */ public class Lautturi { public static void main(String[] args) { try { int[] myNumbers = { 1, 2, 3 }; System.out.println(myNumbers[3]); } catch (Exception e) { System.out.println(e.getMessage()); System.out.println(e); } } }
output:
Index 3 out of bounds for length 3 java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
/** * @author lautturi.com * Java example: try catch example */ public class Lautturi { public static void main(String[] args) { try { System.out.println( 100/0 ); } catch (Exception e) { System.out.println(e.getMessage()); System.out.println(e); } } }
output:
/ by zero java.lang.ArithmeticException: / by zero Exception in thread "main" java.lang.ArithmeticException: / by zero at hello.Lautturi.main(Lautturi.java:68)