课程: Java Practice: Exception Handling

Solution: Catch the exception - Java教程

课程: Java Practice: Exception Handling

Solution: Catch the exception

- [Presenter] Here is my solution to this challenge and I would guess that it's pretty similar to your solution. Our goal is to parse an integer and if it's an invalid integer that we're trying to parse like we have in this source string right here in the sample code, we want to return null if a number format exception is called. The most common way to handle this is through a try-catch block. So I'll type try and then I'm going to wrap this return in curly braces. I'll tab that in and then I'm going to catch the NumberFormatException, and we'll just call this e. And if the exception occurs, we return null. And that's really it. If you hit the test my code button, you should see the correct value return here. And if you want to change the source string to a valid number and test your code, you should see that you actually get the number returned there as well and you get a correct response back in the console.

内容