Java Exceptions: A Brief Introduction

java exceptionsTo understand Jave exceptions, you need to first understand what do we mean by an exception. An exception is anything that disrupts the normal flow of the Java program. Exceptions play an important role in Java programs, since it helps the program to skip the error and continue with the rest of the program. Truly, the error is not skipped; it is just enclosed in an exception object which can then be handled separately by the program. In a not so perfect world, without exceptions a Java program may stop in between due to the error.

You should also know a concept or two about Java before going on with the rest of the article, which will teach you everything you need to know to get started with Java exceptions.

You need to throw an exception in order to handle the exception. After a program throws an exception, the control is transferred to a piece of code that can handle the exception. That piece of code is called the exception handler. There are basically three kinds of exceptions:

  • checked exceptions
  • runtime exceptions
  • errors.

An exception could be thrown deliberately using a throw statement or it could be understood such as an IOException. When the program reaches an exception condition, the control is directly thrown to the catch statement, which then handles the exception and outputs proper condition to the user. Exceptions are of three types: checked, runtime and error. To classify it broadly then there are two kinds of exceptions: checked and unchecked. Runtime and error comes under the category of unchecked exceptions.

Checked exceptions are those exceptions which a programmer cannot predict. It may happen due to a user. For example, if a user wants to access a resource which is not present in its location then the program throws a checked exception. Such exceptions should be handled through code. It is known as checked exception because it is checked by the compiler during compilation. If a method does not extend the proper exception class then the compiler throws an error during compilation itself.

Runtime exceptions happen during runtime and may disrupt the normal functioning of the program.  These exceptions do not require any kind of handling through code. They are general exceptions and the compiler ignores such exceptions. But they may play havoc with your program during runtime, so you should always be ready to take appropriate actions when a runtime error occurs.

Errors come under unchecked exceptions, since a JVM cannot predict when such errors may occur. It may occur due to a crash dump or when the all the recourses of a computer are exhausted.

Classes in Exception

Throwable class is the parent class of the exception class. All the exceptions are subclasses of the java.lang.exception class. The two subclasses of the exception class are the IOException and the RuntimeException class. Another subclass of throwable class is the error class. An error object is thrown in case of system errors such as outofmemoryerror.

To know more about classes take the Introduction to Java training course.

Throwing an Exception

If a method can throw an exception, you need to declare that exception in the method declaration. For example:

public void division (int x, int y) throws BadNumberException {
if (y==0){
throw new BadNumberException (“ Division by zero is not possible”);
}
Return x/y;
}

When the program control reaches the throw clause the lines of code after the throw block is not executed. The program immediately throws an exception and the program control goes towards the catch block which contains code that will handle the exception. Now it’s time for you to see understand try-catch statements:

Try-Catch Block

After the program throws an exception, the control of the program immediately falls towards the catch block. Let’s look at this with an example:

Public void callingDivideFunction() {
Try{
Int result = division (3/0);
System.out.println(result);
} catch (BadNumberException E1){
System.out.println (E1.getMessage());
}
System.out.println (“Division is complete”);
}

In the above example, division by zero is not possible; hence the program throws an exception only to be caught by the catch block. E1.getMessage() will output the error message on the screen. If no exception occurs, the program continues its normal operation without running the catch clause. Hence, in the above example, exception helped to achieve a smooth error free ending of the program without any abrupt endings.

Don’t forget to browse Advanced Java Programming to suffice with this material that you are reading.

Multiple Try-Catch Blocks

A try statement may be followed by one or more catch statements. Depending on the type of exception thrown, multiple catch statements can be made to handle each kind of exception. This functionality in java is well suited to handle multiple exceptions with one try and multiple catch blocks. For example:

try
{
//Some code
} catch (IOException E)
{
//Some code to handle the IOException that occured
} catch (FileNotFoundException E2)
{
//Some code to handle the FileNotFoundException that occurred.
}

The code specifies two kinds of exceptions that the program can handle. If the code in the try statement results in an IOException then the first catch exception is called, whereas for FileNotFound exception the second catch statement is called. Thus, multiple catch block statements bring a little versatility to the whole concept of writing Java programs. Go through the Java Spring Tutorial to learn some interesting uses of the language.

Another important aspect of a Java program is the difference between the throw and the throws keyword. Throws keyword is used in the method signature whereas the throw keyword is used knowingly in a java program to throw an exception. An example of both is provided below:

Public void ABC () throws someException{
//Method Code
throw anotherException;
}

In the above example, the throws keyword, incorporated in the signature of the method, will warn the compiler that the method can throw someException.

If someException is thrown, the control of the program will be transferred to the method that called the ABC function. Suppose that function’s name is DEF. DEF will then run the catch block that is supposed to handle the exception thrown by ABC. In the throw statement, the programmer is deliberately causing the program to throw anotherException.

Finally

The finally statement is written with a try-catch statement is bound to run whether the exception is raised or not. Even if you have a return statement within the try catch block, the program will run the finally statements and then return to program execution. The syntax for try-catch-finally looks like this:

Try {
//some code
}
Catch (exception e1){
}
Catch (exception e2){
}
finally {
//Mandatory code that should always be executed
}

Note: You need to catch an exception raised inside the finally code or else the execution of the program will be interrupted.

You may learn about Java exceptions in detail which will help you get an in depth knowledge about the topic. You should also consider learning Core Java to master these topics.