Throwing and Handling Exceptions

Throwing Exceptions

In Java, we can throw an exception manually using the throw keyword. This is typically done when we want to enforce some custom error handling logic.

Syntax

Example

In this example, we throw an IllegalArgumentException when the age is less than 18.

Handling Exceptions

Java provides a mechanism for handling exceptions using try-catch blocks. We can also use finally to execute code that should run regardless of whether an exception was thrown or not.

Syntax

Example

  • The try block contains the code that might throw an exception.
  • The catch block handles the exception if one is thrown.
  • The finally block will execute whether or not an exception occurred, making it useful for cleanup tasks (like closing a file or releasing resources).

Throwing Custom Exceptions

We can also create custom exceptions by extending the Exception class or one of its subclasses. This allows us to define more specific exception types for our program.

Example

In this example, we create a custom exception InvalidAgeException, which is thrown when the age is under 18.