// handle exceptions where/when they occur public class except2 { public static void main(String args[]) { int a = 1; int b = 0; // Beware of possbile exceptions thrown by a/b: try { System.out.println(a/b); // can't divide by zero } catch (ArithmeticException exception) { System.out.println("You are dividing by zero, fool!"); // exception.printStackTrace(); // see NOTE below } catch (Exception e) { e.printStackTrace(); } finally { System.out.println("Done with division"); } // catch caught the exception thrown by try block // so control returns here: System.out.println("Aren't you glad I accounted for that problem?"); } // method main } // class except2 /* Output: You are dividing by zero, fool! Done with division Aren't you glad I accounted for that problem? */ // NOTE: what happened to variable called exception? Nothing useful...but, // you could have used exception to print out info, like the call stack trace. // the variable exception is a ref to an object of class ArithmeticException // which inherits methods, like printStackTrace(), from Throwable. // So, why bother? Useful for debugging, since catch won't automatically // report the exception. //Notice that the catch blocks go from most specific (an //ArithmeticException) to least specific (an Exception, which is the //parent class of all types of exceptions. //Also, notice the use of the "finally" block. This block always executes, //no matter if an exception is thrown or not.