Search code examples
javaexceptionscjpthrowable

Why can't I handle Exception e with try / catch clause?


When I compile the following code everything goes fine and output is as expected:

class Propogate {
    public static void main(String[] args) {
        Propogate obj = new Propogate();
        try {
            obj.reverse("");
        } catch (IllegalArgumentException e) {
            System.out.println(e);
        } finally {
            System.out.println("That's all folks");
        }
    }
    String reverse(String s) {
        if(s.length() == 00) {
            throw new IllegalArgumentException();
        }
        String reversed = "";
        for(int i=s.length() - 1; i >= 0; --i) {
            reversed += s.charAt(i);
        }
        return reversed;
    }
}

Program results:

java.lang.IllegalArgumentException
That's all folks

However, when I run the exact same code but change the exception type from

IllegalArgumentException to plain old exception all I get is:Propogate.java:14: error:    
unreported exception Exception; must be caught or declared to be thrown
                        throw new Exception();
                    ^
1 error

What is special about the parent type Exception() that I can't handle it with a try / catch statement? Why does IllegalArgumentException() allow me to handle it with a try / catch statement just fine. These are the thoughts of a being kept awake at night with the terror of failing, nay, just taking the SCJP exam.


Solution

  • A method which throws an exception that is not a subclass of RuntimeException must declare that it throws that Exception. You must write

    String reverse(String s) throws Exception {
    

    if you're going to throw an Exception with it. Once you do that, you can catch it with a try/catch normally.