Java Exceptions  «Prev  Next»

Lesson 5Catching exceptions
ObjectiveCatch exceptions

Catching Exceptions in Java

To directly handle an exception without passing it up to a higher context, you must use a try-catch construct.
The syntax for a simple Java try-catch statement in Java 11 is as follows:
try {
  // Code that may throw an exception.
} catch (ExceptionType exceptionName) {
  // Code to handle the exception.
}

The `try` block contains the code that may throw an exception. If an exception is thrown, the runtime system searches for a `catch` block that can handle the exception. If a matching `catch` block is found, the code in that block is executed. If no matching `catch` block is found, the exception is propagated up the call stack.
The `ExceptionType` parameter in the `catch` block specifies the type of exception that the block can handle. The `exceptionName` parameter is a variable that can be used to refer to the exception object. Here is an example of a simple try-catch statement:

try {
  int number = Integer.parseInt("123");
} catch (NumberFormatException exception) {
  System.out.println("The string is not a valid number.");
}

In this example, the `try` block contains the code that may throw a `NumberFormatException`. If the string "123" is not a valid number, the `NumberFormatException` will be thrown. The `catch` block will handle the exception and print a message to the console.
Java 11 introduced a new `try()` syntax that can be used to automatically close resources that are opened in the try block. This can be useful for preventing resource leaks.
Here is an example of the new `try()` syntax:
try (BufferedReader reader = new BufferedReader(new FileReader("myfile.txt"))) {
  String line;
  while ((line = reader.readLine()) != null) {
    System.out.println(line);
  }
} catch (IOException exception) {
  System.out.println(exception.getMessage());
}

In this example, the `try()` block opens a `BufferedReader` resource. The `reader` variable is automatically closed when the `try()` block exits, even if an exception is thrown. The `catch` block handles any `IOException` exceptions that may occur.


You place the code that can potentially throw[1] an exception in the try clause, and then you catch any exceptions that may be thrown in one or more catch clauses[2].

public void readFile() {
  try {
    FileInputStream in = new FileInputStream("Diary.txt");
    // read the file from the stream
  }
  catch (FileNotFoundException e) {
    System.out.println("EXCEPTION -> " + e);
  }
}

Catch clause

In this case only one catch clause is necessary since the FileInputStream constructor is only capable of throwing a FileNotFoundException. The catch clause in this example simply prints information about the exception to standard output. In the context of a real program you might want to include recovery code in the catch clause. You could also print a stack trace for the exception by calling the printStackTrace() method on the exception object.
Note: Each catch clause in a try-catch construct is commonly referred to as an exception handler. It is important to remember that exception handling is not optional.

Handling multiple Exceptions

If a method or section of code throws multiple exceptions, you are required to catch each one of them. For instance, the constructor for the URL class in the java.net package is capable of throwing a MalformedURLException and a SecurityException. Both of these exceptions would need to be handled in catch clauses or in the throws declaration for the method containing the URL object creation. The exception to this rule is if you decide to catch an exception object that is a parent of both exception objects capable of being thrown. As an example, both
  1. MalformedURLException and
  2. SecurityException
are ultimately derived from the Exception class. So you could use one catch clause and handle the generic Exception. This approach, however, gives you less information about the exception that occurred since you are handling the generic Exception type.

java.net

Class MalformedURLException

java.lang.Object
 java.lang.Throwable
 java.lang.Exception
 java.io.IOException
 java.net.MalformedURLException
 
All Implemented Interfaces:Serializable


Exceptions in multi-catch block, but cannot share Inheritance Relationship

Exceptions that you catch in multi-catch block, but cannot share an Inheritance Relationship
What happens if you add another line of code in the previous example, which involves reading from FileInputStream, which might throw an IOException?
Let us add IOException to the list of exceptions being caught in the multi-catch block:
This code fails compilation with the following error message:
This code fails compilation with the following error message:

MultiCatch.java:13: error: Alternatives in a multi-catch statement cannot
be related by subclassing
catch (IOException | FileNotFoundException | SQLException e) {
^
Alternative FileNotFoundException is a subclass of alternative IOException
1 error

NullPointerException Question

Which of the following occasions can cause a NullPointerException? (Choose two options.)
  1. Accessing or modifying the slots of null as if it were an array.
  2. Accessing or modifying the field of a null object.
  3. Trying to access an element of an int array which is not initialized.
  4. When required file is not found.
  5. Trying to create an array with negative number.


Answer: A, B
Explanation : Options A and B are correct. The NullPointerException is thrown when an application attempts to use null in a case where an object is required. These include:
  1. Calling the instance method of a null object.
  2. Accessing or modifying the field of a null object.
  3. Taking the length of null as if it were an array.
  4. Accessing or modifying the slots of null as if it were an array.
  5. Throwing null as if it were a Throwable value.
Option C is incorrect; this will not cause any exception because int array elements are initialized to 0 by default.
Option D is incorrect as in such a case FileNotFoundException is thrown and it is a checked exception.
Option E is incorrect, there we will have NegativeArraySizeException.

If a section of code is capable of throwing an exception, you are required to either pass the exception out of the method using the throws keyword or handle the exception using a try-catch construct.
Careful attention to handling exceptions results in programs that are typically very robust.

Adding Exception Handling - Exercise

Click the Exercise link below to add exception handling to the SquareRoot application.
Adding Exception Handling - Exercise
[1] Throwing (an exception): When an exceptional condition is encountered in a Java program, an exception is thrown, which means that a special exception object is created and passed out of the current context. The idea is that a higher context will be more capable of handling the exception.
[2] Catch clause: The catch clause is the part of the try-catch construct that is used to catch any exceptions that may be thrown by code in the try clause.