Lesson 10 – Exception Handling in Java

A Java program can have two types of errors. The first type of errors occur during compile time before the program executes, for example, missing semi-colon, missing brackets etc. The other type of errors are not caught during compile time and occur during run-time, for instance divide by zero error, array index out of bound error etc. The errors that occur during run-time are also known as exceptions. In this lesson, you will see how to handle the run-time exception and save your program from crashing.

Let’s first see run-time exception in action. Consider the following example:

public class MainClass {

public static void main(String[] args) {
// TODO Auto-generated method stub

int a = 10;
int b = 0;

int result = a /b ;

System.out.println(result);

}
}

In the script above, we have two variables “a” and “b” with values 10 and 0, respectively. We try to divide the value in the variable a by the value in variable b. When you run the above program, you will see the following exception:

Exception in thread "main" java.lang.ArithmeticException: / by zero
	at MainClass.main(MainClass.java:11)

The exception is an arithmetic exception which says that you cannot divide a number by zero.

Try and Catch Blocks

To handle run-time exceptions, "try" and "catch" blocks are used. The code that is likely to throw exception is wrapped inside the "try" block and the code that you want to execute in case of exception is wrapped inside the "catch" block.  Look at the following example:

public class MainClass {

public static void main(String[] args) {
// TODO Auto-generated method stub

try
{
int a = 10;
int b = 0;

int result = a /b ;

System.out.println(result);
}
catch (Exception e)
{
System.out.println(e.getMessage());
}

System.out.println("This code is after the exception");
}
}

When the above code is run, the exception will occur but the program will not crash since we have “try” and “catch” blocks. The program will continue execution even after the exception.

Conclusion

This is the last lesson in our introductory course on Java. Now you should be capable of developing basic Java console applications. From here onward, I would suggest you to chose one of the areas from desktop, mobile or web application development and learn how to use Java for developing desktop, mobile or web applications.