---
title: "How to handle exceptions using try, catch, finally, throw, and throws in Java?"  
description: "Handling exceptions in Java involves using several keywords and constructs."  
author: "Ashutosh Patel"  
published: 2024-07-23  
updated: 2024-07-23  
canonical: https://www.mindstick.com/blog/304526/how-to-handle-exceptions-using-try-catch-finally-throw-and-throws-in-java  
category: "java"  
tags: ["exception handling", "java", "exception"]  
reading_time: 3 minutes  

---

# How to handle exceptions using try, catch, finally, throw, and throws in Java?

Many keywords and constructs are used in handling exceptions in Java. Here’s how you can use `try`, `catch`, `finally`, `throw`, and `throws` effectively,

## Try, catch, finally

\
**try-** This block is used to wrap code that can [throw an exception](https://www.mindstick.com/forum/159351/how-does-a-java-method-throw-an-exception-before-it-s-called).

**catch-** This block is used to handle an exception if it occurs in a `try` block.

**finally-** This section is optional and is used to execute important code such as cleanup code, whether an exception is thrown or not. It executes after `try` and `catch` blocks.

## Syntax

```java
try {
   // Code that may throw an ArithmeticException exception
   int result = divideNumbers(10, 0);
} catch (ArithmeticException e) {
   // Handle the specific exception
   System.out.println("Cannot divide by zero");
   // Optionally, you can re-throw the exception
} catch (Exception e) {
   // Handle any other exceptions not caught by previous catch blocks
   System.out.println("An error occurred");
} finally {
   // Code that executes regardless of whether an exception was thrown or caught
   // Example: Closing resources like files or database connections
   System.out.println("Cleanup code goes here");
}
```

## Example-

```java
class Program {
   public static void main(String[] args) {
       try {
           int result = divideNumbers(10, 0); // Method that throws ArithmeticException
           System.out.println("Result: " + result);
       } catch (ArithmeticException e) {
           System.out.println("Cannot divide by zero");
       } finally {
           System.out.println("Cleanup code here");
       }
   }

   static int divideNumbers(int a, int b)
   {
       return a/b;
   }
}
```

## Output-

```plaintext
Cannot divide by zero
Cleanup code here
```

\
**throw-** This keyword is used to explicitly throw an exception from [your code](https://www.mindstick.com/forum/157976/how-can-you-use-jquery-s-testing-framework-such-as-qunit-to-write-unit-tests-for-your-code).

```java
Example-
public void deposit(int amount) {
   if (amount <= 0) {
       throw new IllegalArgumentException("Deposit amount must be positive");
   }
   // Deposit logic here
}
```

\
**throws-** This keyword is used in the method signature to indicate that the method can [throw one](https://answers.mindstick.com/qa/37238/is-it-possible-to-be-a-successful-pitcher-that-can-only-throw-one-type-of-pitch) or more exceptions. This is part of the method declaration rather than try-catch-finally blocks.

## Example-

```java
public void withdraw(int amount) throws InsufficientFundsException {
   if (amount > balance) {
       throw new InsufficientFundsException("Insufficient funds in your account");
   } else {
       balance -= amount;
       System.out.println("Withdrawal successful");
   }
}
```

#### \
Best Practices

**Catch [specific exceptions](https://www.mindstick.com/forum/160116/concept-of-exception-filters-and-how-can-be-used-to-handle-specific-exceptions-differently)-** Catch specific exceptions first before catching more general exceptions.

**Use finally for cleanup-** Use `finally` for cleanup tasks to be executed whether an [exception occurs](https://www.mindstick.com/forum/159341/how-to-use-try-and-catch-in-java-for-exception-handling-and-what-happens-when-an-exception-occurs) or not.

**Throw appropriate exceptions-** Throw reasonable excuses that fit the situation.

**[Handle exceptions](https://www.mindstick.com/forum/160503/how-can-you-handle-exceptions-in-servlets) appropriately-** Handle exceptions in a way that makes sense for [your application](https://www.mindstick.com/forum/34702/please-tell-me-what-is-cross-site-scripting-and-how-is-it-harmful-for-your-application), whether by logging, retrying, or notifying users on.

\
By [understanding](https://www.mindstick.com/articles/12918/cat-5e-vs-cat-6a-understanding-the-major-differences) and using `try`, `catch`, `finally`, `throw`, and `throws` properly, you can write robust Java code that handles exceptions nicely and maintains reliability.

**Also, Read:** [Differentiate between checked and unchecked exceptions in Java with examples.](https://www.mindstick.com/blog/304521/differentiate-between-checked-and-unchecked-exceptions-in-java-with-examples)

---

Original Source: https://www.mindstick.com/blog/304526/how-to-handle-exceptions-using-try-catch-finally-throw-and-throws-in-java

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
