34. The class Exception and the Operator instanceof try { System.out.print("Line 4: Enter the " + "dividend: "); dividend = console.nextInt(); System.out.println(); System.out.print("Line 7: Enter the " + "divisor: "); divisor = console.nextInt(); System.out.println(); quotient = dividend / divisor; System.out.println("Line 11: Quotient = " + quotient); } catch (Exception eRef) { if (eRef instanceof ArithmeticException) System.out.println("Line 14: Exception " + eRef.toString()); else if (eRef instanceof InputMismatchException) System.out.println("Line 16: Exception " + eRef.toString()); }
35.
36.
37. Rethrowing and Throwing an Exception (continued) import java.util.*; public class RethrowExceptionExmp1 { static Scanner console = new Scanner(System.in); public static void main(String[] args) { int number; try { number = getNumber(); System.out.println("Line 5: number = " + number); } catch (InputMismatchException imeRef) { System.out.println("Line 7: Exception " + imeRef.toString()); } } }
38. Rethrowing and Throwing an Exception (continued) public static int getNumber() throws InputMismatchException { int num; try { System.out.print("Line 11: Enter an “ + "integer: "); num = console.nextInt(); System.out.println(); return num; } catch (InputMismatchException imeRef) { throw imeRef; } } }
39.
40. The Method printStackTrace (continued) import java.io.*; public class PrintStackTraceExample1 { public static void main(String[] args) { try { methodA(); } catch (Exception e) { System.out.println(e.toString() + " caught in main"); e.printStackTrace(); } }
41. The Method printStackTrace (continued) public static void methodA() throws Exception { methodB(); } public static void methodB() throws Exception { methodC(); } public static void methodC() throws Exception { throw new Exception("Exception generated " + " in method C"); } }
42.
43.
44.
45. Creating Your Own Exception Classes (continued) public class MyDivisionByZeroException extends Exception { public MyDivisionByZeroException() { super ("Cannot divide by zero"); } public MyDivisionByZeroException(String strMessage) { super (strMessage); } }