Tutorials  /  JavaScript

Java Catch Multiple Exceptions, Rethrow Exception - Tutorial

Ccentron Redaktion · April 2024 ·2 min read ·JavaScript, Tutorial

In Java 7, the catch block has been improved to handle multiple exceptions in a single catch block. If you are catching multiple exceptions and they have similar code, then using this feature will reduce code duplication. Let’s understand the Java catch multiple exceptions feature with an example.

Java Catch Multiple Exceptions

Before Java 7, we used to catch multiple exceptions one by one as shown below.

Code
catch (IOException ex) {
     logger.error(ex);
     throw new MyException(ex.getMessage());
catch (SQLException ex) {
     logger.error(ex);
     throw new MyException(ex.getMessage());
}

In Java 7, we can catch both these exceptions in a single catch block as:

Code
catch(IOException | SQLException ex){
     logger.error(ex);
     throw new MyException(ex.getMessage());
}

If a catch block handles multiple exceptions, you can separate them using a pipe (|) and in this case, the exception parameter (ex) is final, so you can’t change it. The byte code generated by this feature is smaller and reduces code redundancy.

VM

Matching infrastructure at centron

Node applications need somewhere to run: ccloud³ VMs with full root access from €3.12 per month – or as a managed server if you would rather not run it yourself. Rent a cloud server →

Java Rethrow Exception

Another improvement is done in Compiler analysis of rethrown exceptions. Java rethrow exception allows you to specify more specific exception types in the throws clause of a method declaration. Let’s see this with a small example:

Go
package com.journaldev.util;

public class Java7MultipleExceptions {

    public static void main(String[] args) {
        try{
            rethrow("abc");
        }catch(FirstException | SecondException | ThirdException e){
            System.out.println(e.getMessage());
        }
    }

    static void rethrow(String s) throws FirstException, SecondException,
            ThirdException {
        try {
            if (s.equals("First"))
                throw new FirstException("First");
            else if (s.equals("Second"))
                throw new SecondException("Second");
            else
                throw new ThirdException("Third");
        } catch (Exception e) {
            throw e;
        }
    }

    static class FirstException extends Exception {
        public FirstException(String msg) {
            super(msg);
        }
    }

    static class SecondException extends Exception {
        public SecondException(String msg) {
            super(msg);
        }
    }

    static class ThirdException extends Exception {
        public ThirdException(String msg) {
            super(msg);
        }
    }

}

As you can see in the rethrow method, the catch block is catching Exception but it’s not part of the throws clause. The Java 7 compiler analyzes the complete try block to check what types of exceptions are thrown and then rethrown from the catch block. Note that this analysis is disabled if you change the catch block argument.

Jetzt 200 € Guthaben sichern

Testen Sie Ihr Setup auf ccloud³

Registrieren Sie sich in der ccloud³ und erhalten Sie 200 € Startguthaben für Ihr Projekt – z. B. für eine PostgreSQL-VM mit automatischen Backups.

centron Redaktion Technische Redaktion

Das Redaktionsteam von centron schreibt Anleitungen aus dem Betriebsalltag: getestet auf unserer eigenen Plattform, betrieben im Rechenzentrum in Hallstadt bei Bamberg.

Kategorie JavaScript
Teilen
Noch offene Fragen?

Unser Team hilft Ihnen bei Ihrem konkreten Setup weiter – von Menschen, die die Plattform selbst betreiben.

War dieses Tutorial hilfreich?

Ihre Antwort wird anonym gespeichert und hilft uns, die Tutorials zu verbessern.

Kommentare

Noch keine Kommentare – stellen Sie die erste Frage zu diesem Tutorial.

Zum Kommentieren anmelden

Kommentare stehen centron-Kunden offen. Melden Sie sich in Ihrem Konto an, um eine Frage zu diesem Tutorial zu stellen.

Weiterlesen

Das könnte Sie auch interessieren

Jetzt kostenlos anfangen

Melden Sie sich an und erhalten Sie in den ersten 60 Tagen ein Guthaben von 200 € bei centron.

Dieses Werbeangebot gilt nur für neue Konten. Angebot ausschließlich für Gewerbetreibende.

Jetzt loslegen Sales kontaktieren