Java Fundamentals

Handling Multiple Exceptions

Angie Jones

Angie Jones

Java Champion
Java Fundamentals

Check out a free preview of the full Java Fundamentals course

The "Handling Multiple Exceptions" Lesson is part of the full, Java Fundamentals course featured in this preview video. Here's what you'd learn in this lesson:

Angie demonstrates three ways to handle multiple thrown exceptions, including polymorphism, multiple catch blocks, and catching multiple exceptions in a single block.

Preview
Close

Transcript from the "Handling Multiple Exceptions" Lesson

[00:00:00]
>> Sometimes the Kobe right has the possibility of throwing various exceptions and we wanna be prepared to handle like any of them, right? So, there's three ways that you can handle multiple exceptions at once. You can use polymorphism. I'll show you how to do that? You can use multiple catch blocks.

[00:00:20]
So we only had one before, but we could put two, three, however many we want or you can use a single catch block with multiple exceptions in them. All right, so for polymorphism, you could use a superclass as a way to catch broader exceptions. So look at this example.

[00:00:46]
This is the array index out of bound. Look at the hierarchy there. So array index out of bounds inherits from index, out of bounds exception. Which inherits from runtime exception. Runtime is checked or unchecked?
>> Unchecked.
>> Unchecked, which is exactly why, with the array we see it not declared.

[00:01:07]
It just happens. It's a runtime exception. RuntimeException inherits from exception, who inherits from throwable, and everybody inherits from the lang, which is object. So all of the exceptions that we deal with inherit from that Exception class. So I could do something like, when I did that create new file.

[00:01:34]
We're catching the IOException because that's what the method told us that it might throw. However, if this method threw multiple exceptions, and I wasn't quite sure exactly what exception it was gonna throw, I could use polymorphism. And change that to say I wanna catch exception. If I say exception, exception is the parent of all exceptions.

[00:02:02]
That means any subclass exception that's thrown, this will catch that as well.
>> Would this be where you'd probably want to print whatever message it says to find out exactly where it's failing?
>> Anytime you wanna get the message. You wanna, yeah. Even if it's like the exact exception, you still wanna get the message because it may vary.

[00:02:26]
Even if the exception is the same, it might, the message might vary.
>> Well, I suppose different methods to get up multiple things wrong with them. So, even if you fix one, it doesn't mean you fix everything.
>> Yeah, but an exception is only gonna be thrown for one reason.

[00:02:44]
So I might fix that and then run it again. And another exception might be thrown for another problem, yeah, all right. So another alternative way is to use multiple catch clauses to handle the different types of exceptions. And I'll show you that in our code. So let's write a program that reads decimal numbers from a file and then we're gonna handle two types of exceptions that come from that program.

[00:03:18]
The FileNotFoundException in the InputMismatchExceptions. All right, so this should be fun. We are going to actually to create a file. So I want you to create this as appear to this source directory, so right under whatever your project name is, I want to create a folder first. So new directory is what I want, all right.

[00:03:47]
So let's call this like files. And inside of here, we'll create a new file, and we'll call this numbers.txt, all right, perfect. And let's just throw some numbers one per line you can do decimals, integers. Somewhere in the middle I want you to like throw a random string in there just so they mess things up so I'm gonna just say not a number.

[00:04:34]
And now I'll say 6, oops, 6. Throw a negative in there, all right, say -6, all right. All right, so inside, let's make another class under exceptions package. This one we'll call MultipleExceptionHandling. All right, so, this time, within the main method, we'll create a new file. Don't forget to import file, enter equals new file.

[00:05:38]
All right, [LAUGH] and give it that path. So the path was files/numbers.txt, all right So let's go ahead and make a scanner. So we use scanner before to read from the console, we can also use scanner to read from files as well. So we'll say scanner=new Scanner, and instead of saying system.in, we can just pass the file object.

[00:06:23]
So notice, it's already whining about an unhandled exception. So it says you have an unhandled exception, it's file not found. How do I solve for this again?
>> Try catch.
>> Try catch block, so, let's go ahead and put this within a try block. Then we're going to catch that exception.

[00:06:52]
What was the exception called? FileNotFoundException. So FileNotFoundException, all right, great. Now I want to read from the file, yes? So in order to read from this file, I'm gonna use. Can I rename this? I want to call it fileReader just so you realize that it's not the same like scanner that's reading from the system, all right.

[00:07:34]
So with fileReader, I mean with scanner with everything with this thing you can say has next. And that's just kinda like the iterator where it lets you know if there's some more elements. So this'll let you know if there's another line to read or not, and that of course returns a boolean value of true or false.

[00:07:55]
So we say, while there's more to read, keep reading it in, and then we can just, I don't know. You can do whatever you want, but we'll just print like what we've read, so that we know that it's actually reading from the file. So we can say fileReader.nextDouble.

[00:08:16]
So same thing we've done with the console, we can do with the file. We're expecting numbers right. So let's go ahead we could I don't know in the file not found, let's just print the message that we get there get message. Shall we run it. Are you nervous?

[00:08:48]
It doesn't like this, I ran the wrong one. All right, here we go. So, notice it was able to print out some of the numbers, 3, 2.5, 0, 19.9 but when it got to that string, it threw an exception that says InputMismatchExceptions. Now why did this not complain?

[00:09:18]
Why did the compiler not complain? If it knew that there was a possibility of an exception being thrown?
>> Still a valid input up until a point. We told you that string had doubles.
>> Yeah, but this exception that we have here is an InputMismatchExceptions. I don't see like anything here that's complaining to say like you might get an InputMismatchExceptions.

[00:09:47]
>> Sure, I'm checked exceptions
>> And uncheck the box exception. So next double throws an unchecked exception. That's why we don't have to account for it at all. But we can if we want to all right? So, what we can do here is add another catch block, And this time we'll say okay, if InputMismatchExceptions is thrown.

[00:10:20]
So you can imagine where you could do anything you want. Maybe you wanna say, all right, just skip that line and keep going to the next line or something like that, right? So you can handle this gracefully if you want to. You only read the numbers from the file and not anything else, for example, right, okay?

[00:10:46]
So this is a way that you can handle like multiple exceptions, things like multiple catch blocks there. I'll print the same thing here. I gave you that example but I'm not gonna code that up.
>> If you're just doing the same kind of response can you be combined those catch blocks?

[00:11:07]
>> Yeah, but we're not there yet, okay. All right, so if I wanna use, okay, let's say I got burned by the InputMismatchExceptions, and I'm like, who knows what other unchecked exceptions might occur, right? So maybe I want to also add one third block. And let's add it up top, that says, what, if any exception is thrown, any exception.

[00:11:47]
Go ahead and come here. Now notice, as soon as I added that one I got an error here. On both FileNotFoundExceptions as well as InputMismatchExceptions. And that's because if we think about the hierarchy exception is the parent to both of them. So if I catch this exception, there's no possible way that I would ever get to this block nor this one All right, so if you just wanted to add that you say no, if I get found not found, I want to catch that and I want to create the directory.

[00:12:27]
If I get input mismatch, I want to skip that line and I want to just kind of progress to the next line. But if I get anything else, then I want you to just do something differently, right? You can do this, you just have to put most the highest of them last.

[00:12:56]
Questions on this? All right, so, to your question you can handle like different exceptions with a single catch block. And this will eliminate the duplication like if you see yourself like doing the same thing in multiple catch blocks, then you might want to consolidate those into a single one.

[00:13:24]
So for example, here we are doing the exact same thing, e.printstacktrace in the catch block for found not found exception. We're doing that exact same thing in the catch block for InputMismatchExceptions. So what we could do is put them both together to separate them with a pipe. So this is saying if you find FileNotFound exception or InputMismatchExceptions, notice there's just one name e, either one of these, call it e, and then you can print the stack trace like that.

[00:14:06]
>> Under the hood, would each of those be two separate objects, like each exception is a separate object that just happens to share a name?
>> No, because the exception will only, like one exception is thrown at a time, and so if it matches either one of those, it's just one object.

[00:14:25]
So it just picks whichever one it is makes that object and then carry on.

Learn Straight from the Experts Who Shape the Modern Web

  • In-depth Courses
  • Industry Leading Experts
  • Learning Paths
  • Live Interactive Workshops
Get Unlimited Access Now