try catch Java Block | Exception handling example

Try and Catch are block in Java programming. It’s used for exception handling in Java. Where try block contains a set of statements where an exception can occur and catch block is where you handle the exceptions.

A try block is always followed by a catch block, which handles the exception that occurs in the associated try block.

Java try catch Block Exception handling example

Note: The try-catch block must be used within the method. The try and catch keywords come in pairs:

try catch Java Example

First, see the example code of what is the Problem without exception handling:-

Problem

As you know you can’t divide by zero, so the program should throw an error. It’s only one case, there are a lot of exceptions type in Java.

Output:

Problem without exception handling

Solution: Using try-catch block

As above code, if any error comes your next line will execute. But using a try and catch block will solve this problem.

Output:

Using try-catch block in java

Java try-catch Multiple Exceptions

You can catch multiple exceptions in a series of catch blocks. Let’s see one simple example of using multiple catch blocks.

Output:

ArrayIndexOutOfBounds Exception
Remain codes

Q: Can we use multiple try blocks in exception handling?

Answer: No, you can’t use multiple try blocks with a single catch block. Each try block must be followed by catch or finally. Still, if you use multiple try blocks then a compile-time error is generated.

See below image, IDE itself showing an error:-

multiple try blocks java

Output:

Do comment if you have any doubts and suggestions on this tutorial.

Note: This example (Project) is developed in IntelliJ IDEA 2018.2.6 (Community Edition)
JRE: 11.0.1
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
macOS 10.14.1
Java version 11
All Java try catch Java Example codes are in Java 11, so it may change on different from Java 9 or 10 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.