Skip to content

Exceptions

Introduction

Exception handling is the process of responding to the occurrence of exceptions – anomalous or exceptional conditions requiring special processing - during the execution of a program. In general, an exception breaks the normal flow of execution and executes a pre-registered exception handler.

Rouhly speaking there are three categories of errors: * Syntax errors: arise because the rules of the language have not been followed. * Runtime errors: they are detected by the compiler. Runtime errors occur while the program is running if the environment detects an operation that is impossible to carry out. * Logic errors: occur when a program doesn't perform the way it was intended to.

The exceptions are to catch the runtime and logic errors.

Exception

Exception describes errors caused by your program and external circumstances. These errors can be caught and handled by your program.

System errors

System errors are thrown by JVM and represented in the Error class. The Error class describes internal system errors. Such errors rarely occur. If one does, there is little you can do beyond notifying the user and trying to terminate the program gracefully.

RuntimeException

RuntimeException is caused by programming errors, such as bad casting, accessing an out-of-bounds array, and numeric errors.

Checked Exceptions vs. Unchecked Exceptions

RuntimeException, Error and their subclasses are known as unchecked exceptions. All other exceptions are known as checked exceptions, meaning that the compiler forces the programmer to check and deal with the exceptions.

Unchecked Exceptions

In most cases, unchecked exceptions reflect programming logic errors that are not recoverable. For example, a NullPointerException is thrown if you access an object through a reference variable before an object is assigned to it; an IndexOutOfBoundsException is thrown if you access an element in an array outside the bounds of the array. These are the logic errors that should be corrected in the program. Unchecked exceptions can occur anywhere in the program. To avoid cumbersome overuse of try-catch blocks, Java does not mandate you to write code to catch unchecked exceptions.

Declaring Exceptions

Every method must state the types of checked exceptions it might throw. This is known as declaring exceptions.

public void myMethod()
   throws IOException
public void myMethod()
   throws IOException, OtherException

Throwing Exceptions

When the program detects an error, the program can create an instance of an appropriate exception type and throw it. This is known as throwing an exception. Here is an example:

/** Set a new radius */
public void setRadius(double newRadius) 
    throws IllegalArgumentException {
        if (newRadius >= 0)
            radius =  newRadius;
        else
            throw new IllegalArgumentException("Radius cannot be negative");
}

Catching Exceptions

You can catch different exceptions in different catch blocks. When an exception occurs in try block, the corresponding catch block that handles that particular exception executes. For example if an arithmetic exception occurs in try block then the statements enclosed in catch block for arithmetic exception executes.

try {
    statements;  // Statements that may throw exceptions
} catch (Exception1 exVar1) {
    handler for exception1;
} catch (Exception2 exVar2) { 
  handler for exception2;
}
...
catch (ExceptionN exVar3) {
    handler for exceptionN;
} 

Catch or Declare Checked Exceptions

Java forces you to deal with checked exceptions. If a method declares a checked exception (i.e., an exception other than Error or RuntimeException), you must invoke it in a try-catch block or declare to throw the exception in the calling method. For example, suppose that method p1 invokes method p2 and p2 may throw a checked exception (e.g., IOException), you have to write the code as shown below.

void p1() {
    try {
        p2();
    } catch (IOException ex) {
        ...
    }
}
// catch vs declare
void p1() throws IOException {
    p2();
}

Rethrowing Exceptions

Sometimes we may need to rethrow an exception in Java. If a catch block cannot handle the particular exception it has caught, we can rethrow the exception. The rethrow expression causes the originally thrown object to be rethrown.

try {  
    statements;
} catch(TheException ex) { 
    perform operations before exits;
    throw ex;
}

Finally Clause

A finally block contains all the crucial statements that must be executed whether exception occurs or not. The statements present in this block will always execute regardless of whether exception occurs in try block or not such as closing a connection, stream etc.

try {  
    statements;
} catch(TheException ex) { 
    handling ex; 
} finally { 
    finalStatements; 
}

Exception handling

Exception handling separates error-handling code from normal programming tasks, thus making programs easier to read and to modify. Be aware, however, that exception handling usually requires more time and resources because it requires instantiating a new exception object, rolling back the call stack, and propagating the errors to the calling methods.

When to Throw Exceptions

An exception occurs in a method. If you want the exception to be processed by its caller, you should create an exception object and throw it. If you can handle the exception in the method where it occurs, there is no need to throw it.

When to Use Exceptions

You should use the try-catch block to deal with unexpected error conditions. Do not use it to deal with simple, expected situations. For example, the following code:

try {
    System.out.println(refVar.toString());
} catch (NullPointerException ex) {
    System.out.println("refVar is null");
}
is better to be replaced by :
if (refVar != null)
    System.out.println(refVar.toString());
else
    System.out.println("refVar is null");

Custom Exception

We should use the exception classes in the API whenever possible. If the predefined classes are not sufficient, then you can create custom exception classes. A custom exception classes can be created by extending Exception or a subclass of Exception.

The main reasons for introducing custom exceptions are: * Business logic exceptions – Exceptions that are specific to the business logic and workflow. These help the application users or the developers understand what the exact problem is * To catch and provide specific treatment to a subset of existing Java exceptions

public class MyCustomException extends Exception { 
    public MyCustomException(String errorMessage) {
        super(errorMessage);
    }
}

Custom Unchecked Exception

If we need a custom exception that only be detected during runtime, then we can write a custome unchecked exception. To create a custom unchecked exception we need to extend the java.lang.RuntimeException class.

public class MyCustomUncheckedException extends RuntimeException  { 
    public MyCustomUncheckedException(String errorMessage, Throwable err) {
        super(errorMessage,err);
    }
}
  • Exercise 1: Create your own exception class using the extends keyword. Create a try-catch clause to exercise your new exception.
  • Exercise 2: Create a class with two methods, f( ) and g( ). In g( ), throw an exception of a new type that you define. In f( ), call g( ), catch its exception and, in the catch clause, throw a different exception (of a second type that you define). Test your code in main( ).