Try-Catch Block in Java (With Examples)


In Java, try-catch is used to catch and handle exceptions in a program. You write the code that might cause an exception in the try block. If something goes wrong, the catch block runs to handle it appropriately.. This helps the program keep running instead of stopping. It makes your code safer and easier to manage. You can also use a finally block to execute code regardless of whether an exception occurs.

In this blog, you will learn about try-catch in Java with examples in detail.

Table of Contents:

What are the Exceptions in Java?

Exceptions are the unexpected events that disrupt the normal flow of the program during its execution. When an exception occurs, Java creates an Exception object that has all the details of the error, and then handles the exception using a try-catch block. 

For example, an exception may occur when dividing a number by zero or accessing an invalid array index.

Master Java Today – Accelerate Your Future

Enroll Now and Transform Your Future

quiz-iconquiz-icon



What is Try-Catch in Java?

A Try-Catch block in Java is used to handle exceptions when a program runs, where the code that can throw an exception is placed in a try block, while the code that handles the exception is placed in a catch block. This helps prevent the program from crashing and allows it to continue running or display a meaningful message.

What is Try-Catch in JavaWhat is Try-Catch in Java

Try in Java

The try block in Java is used to write code that might cause an error during the execution of the program, such as dividing by zero. The try block is followed by a catch or finally block, and is used to test the code for errors, not to fix the error itself.

Syntax of Try Block:

try {

    // Code that might throw an exception

}

Catch in Java

The catch block in Java is used to handle errors that occur inside the try block, i.e., if any exception occurs in the try block, the catch block will run and let the program move further instead of crashing. There can be more than one catch block for different types of errors, which can be accessed using e.getMessage() or printed with e.printStackTrace().

Syntax of Catch Block:

try {

    // Code that may throw an exception

} catch (ExceptionType e) {

    // Code to handle the exception

}

Example: Basic Try-Catch

In this example, we will see how a try-catch block works when something goes wrong in the code.

Output:

Basic Try-CatchBasic Try-Catch

Explanation: In the above Java code, the variable number is trying to divide by 0, which is not allowed. Hence, Java throws an ArithmeticException, and the catch block catches the error and prints a friendly message.

Internal Working of Try-Catch Block

When a Java program runs and gets to the try block, the JVM starts executing the code line by line. If no error occurs, the program will skip the catch block and will run normally

However, if an exception occurs inside the try block. Then

Internal Working of Try-Catch BlockInternal Working of Try-Catch Block

1. Java will not execute the remaining lines inside the try block after the line where the error occurred.

2. Java will create an object of the exception class and throw it.

3. Java searches for a catch block whose parameter matches the type of exception thrown in the try block. If it gets one, it gives the object of an exception to that block.

4. The catch block is executed, which allows the program to respond to the error, like showing a message or logging it.

5. If no matching catch block is found, the program will stop, and a stack trace showing the error details will be printed.

6. Once the catch block finishes, Java continues executing the rest of the program.

Get 100% Hike!

Master Most in Demand Skills Now!

Finally in Java

The finally block in Java is used to write the code that should always run, irrespective of what happens in the try or catch block. It is often used to close resources like files, database connections, and runs even if an exception is not thrown or caught, i.e., it will also run if you use return or break in the try or catch.

Syntax:

try {

    // Code that might throw an exception

} catch (ExceptionType e) {

    // Code to handle the exception

} finally {

    // Code that always runs

}

Example: Try-Catch-Finally

In this example, we will see how a Try-Catch-Finally block is executed in Java.

Output:

Try-Catch-FinallyTry-Catch-Finally

Explanation: In the above Java code, the try block causes an exception with the statement “10/0”. The catch block catches the exception in the try block and prints the message. Then, the finally block is executed no matter what happens in the try or catch block.  

Multiple Catch Blocks

More than one catch block is used after a try block to separate different types of exceptions, where each catch block handles a specific type of error. It is mainly used when your try block can throw multiple exceptions, and you want to handle each one of them differently.

Example: Multiple Catch Blocks

In this example, we will discuss how to use different catch blocks after a try block to handle different errors separately.

Output:

Multiple Catch BlocksMultiple Catch Blocks

Explanation: In the above code, the program is using a string that is null, which causes an error. Java looks at each catch block to find the right one and prints the one that matches the error message.

Try with resources

The try block can also be used with resources like files, database connections, or streams that need to be closed after use. Instead of writing extra code to close them, Java does it automatically for you.

Syntax:

try (ResourceType resource = new ResourceType()) {

    // use the resource

} catch (Exception e) {

    // handle exception

}

Example:

Output:

Try with resourcesTry with resources

Explanation: In the above Java code, if the file is not found or cannot be read, then the output will be as above. Otherwise, the line from the file will be printed.

When Not to Use Try-Catch

One should use try-catch only when it is necessary; using them everywhere will only increase the length of your code. It must not be used:

1. When you can check the problems yourself, like checking if a file exists or not, before opening it.

2. When performance is the main attribute of a program, as try-catch can slow the speed of your program.

3. Sometimes it is better to let the exception be handled by the caller, rather than catching it too early.

4. You should not use try-catch for things that can be handled with simple checks. For example, use an if statement to check a condition instead of letting an error happen and catching it.

Try-Finally without Catch Block

In Java, you can also use a finally block with a try block without using the catch block. It is mainly used when you don’t want to handle the exception yourself, but only need to clean up resources, like closing a file. Even if the code has an error, the finally block will be executed.

Example:

Output:

Try-Finally without Catch BlockTry-Finally without Catch Block

Explanation: In the above Java code, the try block runs and throws an exception, but before the program crashes due to the error, the finally block is executed.

Best Practices

1. Do not use try-catch to handle simple conditions, as it makes the code slow and hard to understand.

2. Always catch the most specific exception first, because if you catch a general error first, the specific ones will never run, and the program will not work correctly.

3. Never leave a catch block empty, because leaving it empty can lead to something going wrong that you will not get to know.

4. Always use the finally block to close files or database connections, so that they don’t stay open by mistake.

5. Keep try blocks small, and put only the code that can throw an exception inside the try block.

Unlock Your Future in Java

Start Your Java Journey for Free Today

quiz-iconquiz-icon



Conclusion

In Java, try-catch is used to catch and handle errors so your program does not stop suddenly. You put the code that might cause an error inside the try block. If something goes wrong, the catch block runs to handle it. You can also use a finally block to close files or clean up, no matter what happens. This helps your program run smoothly. 

If you want to learn more about this topic, you can refer to our Java Course.

FAQs on Try Catch in Java – Exception Handling

Q1. What is try and catch in exception handling in Java?

The try statement lets you create a section of code that will be checked for errors as it runs.

Q2. What are the 5 keywords in exception handling?

The 5 keywords in exception handling are: try, catch, finally, throw, and throws.

Q3. What is the difference between try-catch and throws in Java?

Try-catch fixes errors in the method, whereas throws tells the method may cause an error to handle later.

Q4. What is throw and throws in Java?

The throw keyword is used to actually throw an exception, while throws declares that a method can throw exceptions.

Q5. Can we have multiple catch blocks?

Yes, Java allows multiple catch blocks to handle different types of exceptions separately.



Leave a Reply

Your email address will not be published. Required fields are marked *