Java Exception Handling

What is an Exception?

An exception is an error that happens while a program is running.

Without exception handling, the program may stop suddenly. With exception handling, you can respond to the problem and keep the program controlled.

Loading...
Output:

Using try and catch

The try block contains code that might cause an exception.

The catch block runs only if the matching exception happens. This prevents the program from crashing immediately.

Loading...
Output:

Handling Specific Exceptions

Different errors have different exception types. Catching a specific exception makes your error handling clearer and safer.

In this example, accessing an invalid array index causes an ArrayIndexOutOfBoundsException.

Loading...
Output:

Multiple catch Blocks

A single try block can have multiple catch blocks for different exception types.

More specific exceptions should come before general exceptions like Exception.

Loading...
Output:

The finally Block

The finally block always runs after try and catch, whether an exception happens or not.

It is commonly used for cleanup tasks, such as closing files, scanners, or database connections.

Loading...
Output:

Using throw

The throw keyword is used to manually create an exception.

This is useful when you want to stop invalid data from being accepted, such as an invalid age, price, or score.

Loading...
Output:

Using throws

The throws keyword is placed in a method header to show that the method might throw an exception.

This is often used with checked exceptions, where Java requires the error to be handled or declared.

Loading...
Output:

Checked vs Unchecked Exceptions

Java has two major categories of exceptions: checked and unchecked.

Checked exceptions must be handled with try-catch or declared with throws. Unchecked exceptions usually happen because of programming mistakes at runtime.

  • Checked: FileNotFoundException, IOException
  • Unchecked: ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException

Common Java Exceptions

Knowing common exception types helps you understand what went wrong and how to fix it.

  • ArithmeticException: math error, like dividing by zero
  • NullPointerException: using an object that is null
  • ArrayIndexOutOfBoundsException: accessing an invalid array index
  • NumberFormatException: converting invalid text to a number
  • FileNotFoundException: trying to open a file that does not exist

Practice

Create a program that asks the user for two numbers and divides them. Handle invalid numbers and division by zero.

Loading...
Output:

Need Help?