Tuesday 10 May 2016

Throwable and Error classes should not be caught

Throwable is the superclass of all errors and exceptions in Java. Error is the superclass of all errors which are not meant to be caught by applications.

Catching either Throwable or Error will also catch OutOfMemoryError or InternalError from which an application should not attempt to recover.
Only Exception and its subclasses should be caught.


try { /* ... */ } catch (Throwable t) { /* ... */ }    // Non-Compliant
try { /* ... */ } catch (Error e) { /* ... */ }        // Non-Compliant
try { /* ... */ } catch (Exception e) { /* ... */ }    // Compliant

Catch Exception instead of Error.

Why should we not caught Throwable and Error?

Usually Errors are problems you cannot possibly recover from, like OutOfMemoryError. There's nothing to do by catching them, so you should usually let them escape, and bring down the virtual machine.

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...