exceptions

All exceptions in Java are derived from the Throwable class, which has two main subclasses:

  • Error : severe and typically unrecoverable errors (e.g. OutOfMemoryError)

  • Exception : exceptions that are recoverable and can be caught and handled.

Error vs Exception

Error
Exception

Unchecked exception

Checked & Unchecked exception

Caused by environment of application

Caused by application

During run-time

During compile time or run-time

Checked vs Unchecked exception

Checked exception

aka. compile time exception

must be either caught (try-catch) or declared in the method signature using the throws keyword.

Unchecked exception

aka. run time exception

Do not need to be explicitly caught or declared. They typically indicate programming error that should be addressed

Java Exception Hierarchy

Java Exception Hierarchy

Handling Exceptions

Note , can use generic "Exception" class since all exceptions extend from it or use a specific exception

try , catch , finally

throw

Explicitly throw an exception

throws

Custom Exception

Can add custom functionalities for custom exception

Last updated