Do we have to mention exception type in java?

106 views Asked by At

I just found

try  
{ 
    Thread.sleep(50); 
} catch(Exception ex){  }  

works just fine. Then why do we need to explicitly mention the exception type?

try  
{ 
    Thread.sleep(50); 
} catch(InterruptedException ex){ex.printStackTrace();}   
2

There are 2 answers

0
T.J. Crowder On

Why do we explicitly mention exception type?

To control which exceptions we catch. Exceptions which aren't of the defined class (or a subclass of it) will propagate to the caller. So for instance, I can say I'm going to handle an IOException in my code, but if a FooBarException occurs, I'll leave it for the caller to handle.

I recommend reading through the Java exceptions tutorial.

1
Mureinik On

A catch clause will commence if the given type of exception is thrown, or any of its subclasses. Exception isn't a special keyword - it's a name of a class - java.lang.Exception, from which all checked exceptions inherit. If you want to catch any exception, including unchecked exceptions, you could use catch (Throwable t). Although note this is rarely a good idea.