DEV Community

Dinesh G
Dinesh G

Posted on

Exception Handling in Java

Introduction

Java exceptions are events that disrupt the normal flow of a program during runtime.

Java exceptions are events that disrupt the normal flow of a program during runtime. They are objects representing errors or unusual conditions that the program should handle to prevent crashing or unexpected behaviour.

When:

You should use exception handling to manage conditions that are outside the normal ,expected flow of a program.

Why:

Exception handling is crucial for writing reliable and robust applications

  • Preverts abnormal program termination
  • Provides meaningful error message
  • Ensure resources cleanup
  • Promotes code robustness

Types of Java Exceptions

1.Checked Exceptions

These are exceptions that are checked at compile time

The program must handle these exceptions using a try-catch block or declare them using the throws keyword.

Examples: IOException, SQLException, FileNotFoundException.

2.Unchecked Exceptions

These occur during runtime and are not checked at compile time.

They usually result from programming errors, such as logic mistakes or improper use of APIs.

Examples: NullPointerException, ArrayIndexOutOfBoundsException, ArithmeticException.

3.Errors

Represent serious problems that applications should not try to catch.

Examples: OutOfMemoryError, StackOverflowError.

Exception Handling in Java

try: Code that might throw an exception is enclosed in a try block.

catch: Handles specific exceptions thrown by the try block.

finally: Block that is always executed after try and catch, regardless of whether an exception occurred.

throw: Used to explicitly throw an exception.

throws: Declares exceptions that a method might throw.

Syntax Example

import java.io.*;

public class ExceptionExample {
    public static void main(String[] args) {
        try {
            // Code that may throw an exception
            FileInputStream file = new FileInputStream("test.txt");
        } catch (FileNotFoundException e) {
            // Handling the exception
            System.out.println("File not found: " + e.getMessage());
        } finally {
            // Always executed
            System.out.println("Execution completed.");
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Commonly Used Exception Classes

  • IOException: Input-output operations failure.
  • SQLException: Database access errors.
  • ClassNotFoundException: Class not found during runtime.
  • ArithmeticException: Invalid arithmetic operations (e.g., division by zero).
  • NullPointerException: Attempt to use an object reference that is null.
  • IllegalArgumentException: Method has been passed an inappropriate argument.

Custom Exceptions

You can create custom exceptions by extending the Exception or RuntimeException class.

class MyCustomException extends Exception {
    public MyCustomException(String message) {
        super(message);
    }
}

public class CustomExceptionExample {
    public static void main(String[] args) {
        try {
            throw new MyCustomException("Custom error occurred");
        } catch (MyCustomException e) {
            System.out.println(e.getMessage());
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Different Types of Exceptions

In Java, there are different kinds of problems, or exceptions. For example:

`ArithmeticException`: When you try to do math that doesn’t make sense, like dividing by zero.
`NullPointerException`: When you try to use something that doesn’t exist yet (like trying to open a treasure chest that isn’t there).
`ArrayIndexOutOfBoundsException`: When you try to reach into an array for something that's beyond its limits, like asking for the 11th cookie in a jar that only has 10.
Enter fullscreen mode Exit fullscreen mode

Cleaning Up and Making Custom Exceptions

The finally Block

Imagine you’re playing a game and you find treasure, but whether you succeed or not, you always want to close the treasure chest when you're done. In Java, the finally block is like making sure the treasure chest is always closed, no matter what happens.

What is the finally Block?

The finally block is a piece of code that always runs, whether an exception happens or not. It’s used to clean up, like closing a file, stopping a timer, or putting away the treasure chest.

Let’s See an Example:

public class FinallyExample {
    public static void main(String[] args) {
        try {
            int result = 10 / 0; // This will cause an exception.
        } catch (ArithmeticException e) {
            System.out.println("Oops! You can’t divide by zero.");
        } finally {
            System.out.println("This will always run, no matter what.");
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Here’s what happens:

  • The try block tries to do something risky.
  • The catch block catches the problem if it happens.
  • The finally block always runs, even if there’s no problem.

Top comments (0)