Exception Handling Practice Problems


  1. The following code segment will cause the program to crash due to a NullPointerException being thrown. Modify the code so that the size assignment statement is surrounded by a try/catch such that the code will set the value of size to 0 when the exception is thrown rather than crash.
       String str = null;
       int size;
           size = str.length;

  2. Write a method called addTwoPositive that takes two int parameters, and if either value is not positive, throw an ArithmeticException, passing the String "Non-positive integers sent!" to the constructor of the exception. If the values are both positive, then return the sum of them.

  3. Under what circumstances will the finally code block be executed in a try/catch/finally code segment?