Catching Exceptions
As mentioned earlier, there are two ways to handle exceptions: catching and throwing. In this section, we will deal with the first of these methods. Catching an exception requires encapsulating the code that might generate an unwanted result into a specific statement, as shown in the following code snippet:
try { // code that could generate an exception of the type ExceptionM } catch (ExceptionM e) { // code to be executed in case of exception happening }
We can put this code to test with any of the previous examples. Let's demonstrate how we could stop the exception we found in the first example of the chapter, where we tried to check the length of a string that was initialized to null:
public class Example07 { public static void main(String[] args) { // declare a string with nothing inside String text = null...