public class CatchingExceptions {
    private int erroneousMethod(int p) {
        if (p == 0) {
            throw new IllegalArgumentException();
        }
        int x = 0x01;
        return p / (x >> Math.abs(p)); // this line will throw!
    }

The task is to implement the following method to catch and print the two exceptions.

public void catchExceptions(int passthrough) {

        erroneousMethod(passthrough); // will throw!
        try{
          ????
        } catch (IllegalArgumentException e){
            System.out.println("???? ");
        }
}
1

There are 1 best solutions below

0
Bohemian On

Call the method inside the try block:

public void catchExceptions(int passthrough) {
    try{
        erroneousMethod(passthrough);
    } catch (RuntimeException e) { // catches all unchecked exceptions
        String message = e.getMessage() == null ? "" : (": " + e.getMessage());
        System.out.println(e.getClass().getSimpleName() + ": " + message);
    }
}