DEV Community

Cover image for Exception Handling in Java
Bharath S R
Bharath S R

Posted on

2

Exception Handling in Java

Introduction

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.

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

Java uses the following keywords for exception handling:

  1. try: Code that might throw an exception is enclosed in a try block.
  2. catch: Handles specific exceptions thrown by the try block.
  3. finally: Block that is always executed after try and catch, regardless of whether an exception occurred.
  4. throw: Used to explicitly throw an exception.
  5. 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

Summary

Java exceptions are critical for handling errors and maintaining application stability. They are categorized into checked exceptions (like IOException) that are handled at compile-time, unchecked exceptions (like NullPointerException) that occur during runtime, and errors (like OutOfMemoryError) indicating serious issues.

Java's robust exception-handling mechanism includes keywords like try, catch, finally, throw, and throws, allowing developers to manage errors gracefully. Custom exceptions can also be created to address application-specific issues. By effectively leveraging Java's exception handling, developers can build resilient and user-friendly applications. Happy Coding!!

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay