{

Java Multi catch block exception handling example tutorial


java exception handling multi catch block

Java 7 Exception Handling

Java7 language has introduced features like Usage of Strings in Switch case and improved the exception handling.

It introduced a multi-catch block.

A single catch block is not sufficient to handle multiple exceptions before Java 7.

We can achieve this using multiple catch block, where each catch block is used to catch a single exception.

Let us see the example of Java7 Multi-catch exception example

Let’s see how multiple exceptions are handled before the Java7 version

How to declare multiple exceptions in catch block in java?

For example, before Java 7, if we want to catch multiple exceptions, we need to write a separate catch block for each exception type as shown below.

public class Test {
    public static void main(String[] args) {
        try{
            // possible code throwing exception   
        }catch(IllegalArgumentException iae){
            //catch  IllegalArgumentException and print error message  
        }catch(Exception iae){
            //catch  Exception and prints error message  
        }
    }
}

Java 7 introduced multiple exceptions declared in the single catch block.

Handling multiple exceptions example in Java 7

Java7 has introduced a single catch block for handling multiple exceptions.

Altogether, It reduces the code of catch blocks.

Below example

public class Test {
    public static void main(String[] args) {
        try{
            // possible code throwing exception  
        }
        catch(IllegalArgumentException iae|Exception e) {
        }



    }
}

In the above code, IllegalArgumentException and Exceptions are defined in the same catch block with separator pipe | symbol

Advantages of Multi-catch exceptions in Single catch block:-

  • Simplify the coding
  • Decrease code duplicate
  • Reduces catch blocks

Support multi-catch exceptions in Maven projects of Intelli

When you’re working on maven projects in Intelli IDE, you can configure the java version to maven compiler plugin with the following details.

change source and target java version at least 1.7

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.6.1</version>
    <configuration>
          <source>1.9</source>
          <target>1.9</target>
    </configuration>
</plugin>

Conclusion

Learned multi-catch block in Java 7 language and how to configure in maven or Intelli to support it.

THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.