课程: Java Practice: Exception Handling

Solution: Hidden Exception - Java教程

课程: Java Practice: Exception Handling

Solution: Hidden Exception

- [Instructor] Here is one solution to the challenge. I'm going to start by hiding my test code area because I don't need to modify it for this movie. In here in the answer area, we have method C that's throwing an exception, which is called by method B, which is called by method A, which has an incomplete try-catch statement. Sometimes ignoring a catch is fine. Other times, when you're calling it through a chain, you could actually lose exceptions that are thrown when you call from the root method. One way around that is to throw the exception again in a place like here. And I could just put the same code that's in here, or use the exception getMessage method to get the original message, but what I'm going to do instead is actually remove the try and the catch, and the reason for that is that this exception will get thrown, and it will get caught all the way up here. So again, this is one of multiple ways of solving this challenge. The choice is yours depending on your situation. I'm going to hit Test My Code, and sure enough, it works. So remember, whether or not you decide to handle your exceptions in the real world in this exact way, it's almost always better to not ignore exceptions when you have them called in a chain.

内容