Exception handling in Java

Saurav Kumar
7 min readSep 20, 2023

Exception handling in Java allows us to gracefully handle errors or exceptional situations that may occur during program execution. Java uses a try-catch block to handle exceptions. Here’s a basic overview:

1. Try Block: You enclose the code that might throw an exception inside a ‘try’ block.

try{
// Code that may throw an exception
}catch(ExceptionType1 e1){
// Handle ExceptionType1
}catch(ExcpetionType2 e2){
// Handle ExceptionType2
}finally{
//Optinal: Code that runs regardless of whether an exception occured or not
}

2. Catch Block: You can have multiple ‘catch’ blocks to handle different types of exceptions. The catch blocks are evaluated in order, and the first one that matches the thrown exception’s class is executed.

3. Finally Block: The ‘finally’ block is optional and is used for code that must be executed regardless of whether an exception is thrown or not.

4. throw:

  • ‘throw’ is a keyword in Java used to throw an exception within your code explicitly. It is used when you encounter an exceptional situation that you want to handle or propagate as an exception.
  • You use ‘throw’ followed by an exception object to indicate that a specific exception has occurred.
if(someCoditionIsMet){
throw new

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

Saurav Kumar
Saurav Kumar

Written by Saurav Kumar

Experienced Software Engineer adept in Java, Spring Boot, Microservices, Kafka & Azure.

No responses yet

What are your thoughts?