CodeGym /Courses /New Java Syntax /How multi-catch works

How multi-catch works

New Java Syntax
Level 15 , Lesson 7
Available
How multi-catch works - 1

"A few more interesting lessons. Oh, how I love teaching!"

"I'd like to tell you about how multiple catch blocks work. It's very simple: when exceptions occur in a try block, execution moves to the first catch block."

"If a type indicated in the parentheses of the catch block matches the type of the thrown exception, then execution starts inside that block. Otherwise, we move to the next catch block, where the same check is performed."

"If we run out of catch blocks and the exception hasn't been caught, it will be rethrown, and the current method will terminate abnormally."

"I see. The catch block that coincides with the exception type will be the one executed."

"Yes, right. However, in reality it's a bit more complicated. Classes can inherit other classes. If a Cow class inherits an Animal class, the Cow object may be referenced not only by a Cow variable, but also by an Animal variable."

"And?"

"Because all exceptions inherit Exception or RuntimeException (which also inherits Exception), they can still be caught using 'catch (Exception e)' or 'catch (RuntimeException e)'."

"And?"

"We can make two conclusions. First, you can use 'catch (Exception e)' to catch any exception. Second, the order of catch blocks matters."

"Here are some examples:"

"The ArithmeticException that occurs after we divide by 0 will be caught in the second catch block."

Code
try
{
    System.out.println("Before calling method1.");
    int a = 1 / 0;
    System.out.println("After calling method1. This will never be shown.");
}
catch (NullPointerException e)
{
    System.out.println("Null reference. Exception has been caught.");
}
catch (ArithmeticException e)
{
    System.out.println("Division by zero. Exception has been caught.");
}
catch (Exception e)
{
    System.out.println("Any other errors. Exception has been caught.");
}

"In the example below, the ArithmeticException will be caught in the first catch block, because all exceptions inherit Exception, i.e. Exception covers all exceptions."

Code
try
{
    System.out.println("Before calling method1.");
    int a = 1/0;
    System.out.println("After calling method1. This will never be shown.");
}
catch (Exception e)
{
    System.out.println("Any other errors. Exception has been caught.");
}
catch (NullPointerException e)
{
    System.out.println("Null reference. Exception has been caught.");
}
catch (ArithmeticException e)
{
    System.out.println("Divided by zero. Exception has been caught.");
}

"In the example below, ArithmeticException won't be caught. It will be rethrown to the calling method."

Code
try
{
    System.out.println("Before calling method1.");
    int a = 1/0;
    System.out.println("After calling method1. This will never be shown.");
}
catch (NullPointerException e)
{
    System.out.println("Null reference. Exception has been caught.");
}

"That cleared things up a bit. These exceptions are not the easiest topic."

"It only seems that way. They actually are one of the simplest things in Java."

"I don't know whether to be happy or sad about that…"

Comments (30)
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION
Anonymous #10775689 Level 14, United Kingdom
2 August 2021
Chapter 11 in Head First Java has great examples/explanations of exceptions.
Syed Umar Level 1, Gothenburg , Sweden
7 March 2021
Wasn't this explained in previous lesson? That it's a feature introduced in Java 1.7
Agent Smith Level 38
20 August 2020
Instead of having to catch each exception type individually, you can use a single catch clause to handle the exceptions without code duplication.

catch(ArithmeticException | ArrayIndexOutOfBoundsException e) // example
Andrei Level 41
11 November 2020
What would be the advantage of using your described method vs just putting (Exception e) in the catch method?
Agent Smith Level 38
11 November 2020
Well, it all depends on what you are trying to achieve. Putting "Exception e" there instead will catch any and all Exceptions, which sometimes might not be the desired thing, bacause maybe you only want to catch specific exceptions. In that case you are able to do so with less code.
Andrei Level 41
11 November 2020
Aha, that makes more sense. So you are saying, maybe I want some exception to not be caught so they stop the program because they are important to the outcome I want to get from the program?
Jcode Level 27, United Kingdom
12 February 2022
In the example we are 'catching' ArithmeticException | ArrayIndexOutOfBoundsException e. We can then write specific code inside the curly braces{} which is specific to those exceptions. take a look at ... multi-catch
Aakankasha Sharma Level 19, Chandigarh, India
23 June 2020
If the function does not have checked exceptions, and an exception is thrown, does that function still throw it to calling function until it exits main (or it is caught somewhere), or terminates at that point where the exception got thrown itself? I remember reading instances of it in the first lectures but haven't got the grasp of it...
Viktor Blank Level 14, Berlin, Germany
9 January 2020
"In the example below, the ArithmeticException will be caught in the first catch block, because all exceptions inherit Exception, i.e. Exception covers all exceptions." In the second code block,right?
9 January 2020
yeah
Viktor Blank Level 14, Berlin, Germany
9 January 2020
Was firstly kinda confused if i've understood exceptions correct..
10 January 2020
we gotta learn a lot!
horst Level 26, Not in list
14 January 2020
I think the statement is not perfectly clear, but it is correct nevertheless. What they want to show is that the order of the catch-blocks matters. As every specific exception is a child of the Exception class, the first catch block with the very generic Exception will be executed even though you have a more specific catch-block following afterwards. So in this case, the compiler will not search through all your catch-blocks and pick the most accurate/specific/narrow one, but the first one that fits anyway. (And Exception always fits) On the upside: you can catch any exception using the very broad Exception class without having to think about much. On the downside: you lose information on the type of exception that is occurring and only get a very general report. (In this case: "Any other errors. Exception has been caught.")
sean huang Level 15, New York City, United States
13 June 2020
Yeah I think they meant the first catch block
Angel Li Level 18, Fremont, United States
23 June 2020
It says example BELOW. I think you are looking at the example above not below.
Dawn( #11020889) Level 37, Toronto, Canada
12 September 2022
very clear explanation!
Janusz Level 11, Radomsko, Poland
2 December 2019
It went quickly but ... how do I know what exception to raise. I made a general exception in the intellij, and the correct one was displayed there. I don't know if it's OK but it works.
Alexandre Lalancette Level 41, Quebec, Canada
6 November 2019
This is the easiest level so far... Just an if-else statement thing
Renat Mukhametshin Level 16, Pervouralsk, Russain Federation
1 August 2019
good theme!! hey, invite me to your friends and we will learn together!! and help each other
Voris Level 10, Tashkent, Uzbekistan
14 July 2019
If (Exception e) covers all exceptions why not to use always only this one.
Joey Purdon Level 13, United States
27 July 2019
To give the user or programmer more information as to why the exception occurred. A general exception wouldn't give as much information to track down what went wrong.
Mecs Level 17, Budapest, Hungary
18 October 2020
What if you want to handle several different types of exceptions in a different way? This way we can specify them in separate catch blocks. Recommended order is most specified --> general.
Ewerton Level 30, Belo Horizonte, Brasil
28 June 2019
It is like an "else if".
9 January 2020
yeah with new names!