---
title: "How do you handle exceptions in Java with example?"  
description: "How do you handle exceptions in Java with example?"  
author: "Anubhav Sharma"  
published: 2024-07-18  
updated: 2024-08-13  
canonical: https://www.mindstick.com/forum/160954/how-do-you-handle-exceptions-in-java-with-example  
category: "java"  
tags: ["java", "javac"]  
reading_time: 3 minutes  

---

# How do you handle exceptions in Java with example?

How do you [handle exceptions](https://www.mindstick.com/forum/159234/how-do-you-handle-exceptions-using-the-try-catch-block-in-java) in [Java](https://www.mindstick.com/articles/12214/web-development-company-in-india-laid-on-the-foundation-of-concrete-java-programming) with example?

## Replies

### Reply by Ravi Vishwakarma

Exceptions are handled using a combination of `try`, `catch`, `finally`, and `throw` statements. Here's a detailed overview of how to [handle](https://www.mindstick.com/articles/311004/suede-skillet-handle-cover) exceptions in Java, including an example.

## Basic Exception Handling

**Try Block**: Code that might throw an exception is placed inside a `try` block. If an exception occurs, the code execution immediately jumps to the corresponding `catch` block.

**Catch Block**: This block catches the exception thrown by the `try` block. You can have multiple `catch` blocks to handle different types of exceptions.

**Finally Block**: This block is optional and is used for code that must execute regardless of whether an exception was thrown or not, such as closing resources.

**Throw Statement**: Used to explicitly throw an exception from a method or block of code.

**Throws Clause**: Used in method declarations to specify that a method can throw certain types of exceptions.

## Example

Here is an example of handling exceptions in Java. This example demonstrates handling an arithmetic exception and a file not found exception.

```java
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;

public class ExceptionHandlingExample {
    public static void main(String[] args) {
        // Example of handling an arithmetic exception
        try {
            int result = 10 / 0; // This will throw ArithmeticException
        } catch (ArithmeticException e) {
            System.out.println("Error: Division by zero is not allowed.");
        } finally {
            System.out.println("This will always execute.");
        }

        // Example of handling a file not found exception
        try {
            PrintWriter writer = new PrintWriter(new File("nonexistentfile.txt"));
            writer.println("This will not be executed.");
            writer.close();
        } catch (FileNotFoundException e) {
            System.out.println("Error: File not found.");
        } finally {
            System.out.println("This will always execute, even if the file was not found.");
        }

        System.out.println("Program continues...");
    }
}
```

## Output:

```plaintext
Error: Division by zero is not allowed.
This will always execute.
Error: File not found.
This will always execute, even if the file was not found.
Program continues...
```

## Explanation

**Arithmetic Exception Handling**:

- The `try` block attempts to divide a number by zero, which throws an `ArithmeticException`.
- The `catch` block catches the exception and prints an error message.
- The `finally` block is executed regardless of whether an exception was thrown, ensuring that the code within it runs.

**File Not Found Exception Handling**:

- The `try` block attempts to open a file for writing. Since the file does not exist, it throws a `FileNotFoundException`.
- The `catch` block catches the exception and prints an error message.
- The `finally` block is executed regardless of the exception, ensuring that the code within it runs.

### Summary

- `try` **Block**: Contains code that might throw an exception.
- `catch` **Block**: Catches and handles exceptions.
- `finally` **Block**: Executes code that must run regardless of whether an exception was thrown.
- `throw` **Statement**: Used to explicitly throw an exception.
- `throws` **Clause**: Used in method signatures to declare that a method can throw exceptions.

Exception handling is crucial for building robust Java applications, allowing you to manage errors gracefully and maintain program flow.

## Read more

[**Explain the difference between checked and unchecked exceptions. Provide examples.**](https://www.mindstick.com/forum/160948/explain-the-difference-between-checked-and-unchecked-exceptions-provide-examples)

[**How to prevent the NullReferenceException in C#?**](https://www.mindstick.com/forum/160706/how-to-prevent-the-nullreferenceexception-in-c-sharp)

[**Importance of logging and reporting exceptions in a .NET Core API.**](https://www.mindstick.com/forum/160115/importance-of-logging-and-reporting-exceptions-in-a-dot-net-core-api)


---

Original Source: https://www.mindstick.com/forum/160954/how-do-you-handle-exceptions-in-java-with-example

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
