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();}
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.
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 aFooBarException
occurs, I'll leave it for the caller to handle.I recommend reading through the Java exceptions tutorial.