课程: Java Practice: Exception Handling

Solution: Nested Exceptions - Java教程

课程: Java Practice: Exception Handling

Solution: Nested Exceptions

- [Instructor] Here is one solution to this challenge. So we have a method throwing an exception. So if you look at how the code runs, it's this chain of methods, and each one free-throws the exception with its own method name inside of the exception message. And then we're handling that at the top. But if I were to capture the message here, it would just get the exception thrown in method A. That's because every time it's re-thrown, that name changes from the original. So how do we access the original method? One way to do that is through the stack trace. So let's take a look at how that works. And this time I'm actually going to paste in some code instead of writing it from scratch. And then I have some imports to add. So I'm going to add all of them. Once those are imported, I'll go back to my code. And what I'm doing is grabbing the stack trace using that helper method, get stack trace as string, which looks like this, and then I'm grabbing all of the causes by using a stream filter. So I'm taking that stack trace that's returned, splitting it on each line, and then only grabbing values that contain exception and method, and then taking the last one. And that's going to give me exception in method C. I'll hit test my code and, sure enough, it works. So of course, that's one solution to this challenge. And there are many solutions, but the most important takeaway here is the source of the problem is found in the stack trace.

内容