Exception Handling Exercises

  < Previous  Next >
  1. Discuss with your neighbor the following question: Do you have to have a catch-block after a try-block? Why or why not?
  2. Will the catch-block always execute? What about the finally-block?
  3. Write a complete Java program that repeatedly requests two numbers from the user, performs integer division with the two numbers and displays the result. For example, entering 22 and 7 would result in:
    Please enter a number: 22
    Please enter another number: 3
    22 divided by 3 equals 7
    Thank you, bye :)	    
    
    Also, entering 22 and three first would result in:
    Please enter a number: 22
    Please enter another number: three
    Sorry, there was an error parsing your input.
    Please enter another number: 3
    22 divided by 3 equals 7
    Thank you, bye :)
    Furthermore, entering 22 and 0 first would result in:
    Please enter a number: 22
    Please enter another number: 0
    Arithmetic exception: / by zero
    	    
    Please enter a number: 22
    Please enter another number: 3
    22 divided by 3 equals 7
    Thank you, bye :)
  4. Match the appropriate unchecked exception with the code that would throw it:
    1. ArithmeticException
    2. ClassCastException
    3. IOError
    4. IllegalArgumentException
    5. IndexOutOfBoundsException
    6. NullPointerException
    1. Scanner stdinScanner;
      stdinScanner.nextInt();
    2. int[] values = new int[100];
      System.out.println( values[100] );
    3. int num1 = 10;
      int num2 = 0;
      System.out.println( num1 / num2 );
    4. String number = "twenty-one";
      Double num = (Double)number;
    5. new Long("");