What is a Java exception?

An exception is an error or event that occurs during a program execution if something unexpected or unhandled occurs in Java program. Depending on the error type, the Java exceptions may crash a program or result in some unexpected behavior.

In order to avoid crashing or ending a program in an unwanted way, the Java error must be handled immediately.

For example, your program takes an input as a number from the end-users and, by mistake, a string is entered. This may raise an exception and the normal flow of application will not be maintained.

What you can do, in that case, take the user input, place it in the exception handling area and verify if only numbers are entered. If strings are entered then you should know the error code and throw an appropriate message to the user to re-enter in the correct format.

Exceptions in Java are handled with Java try catch block.

An example of exception handling

Java Exception

Exceptions of Java can be categorized into following:

1-      Checked exceptions

The checked exceptions are those that can happen due to the user’s mistake or action. As a programmer, one should check all possibilities a user can make and handle it properly. For example, your program takes user file as input, where a user specifies the path. What if the file does not exist? It will create an error and you should know in advance what the error will be and should let the user know what went wrong.

The exceptions in this category are checked at the compile time. The classes, apart from the RuntimeException and Error that extend the Throwable class comes under checked exception category. For example IOException.

2-   Java Runtime Exceptions

Java Runtime exceptions are those that occurs at runtime. The compiler does not pick these exceptions. So, this is simply at programmers part to diagnose and fix/handle it. For example, an array element being accessed that does not exist.

3-   Java Error

This category of exception is generally unavoidable or does not happen due to the fault of programmer or user. For example, users machine ran out of resources and is too less for JVM.

The Exception classes

The main class is the Java.lang.Throwable. All other exception classes are the subclasses of the Throwable class.

The hierarchy is as follows:

Parent class = Throwable

Exception and Java Error classes extend the Throwable.

IOException, RuntimeException, and SQLException extend the Exception class.

ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException, ClassCastException, and others are the sub-classes of the RuntimeException.

Exception handling in Java

If you feel your code can produce an error, you can raise an exception in Java. Raising an exception in Java is quite simple.

The try catch block

Java comes up with the try-catch keyword combination that is used to handle exceptions in Java. Any code you feel can create problems or produce error can be placed inside the try catch block. You can pick(catch) that Java error code and show some appropriate output while keep running the program normally.

Syntax of using Java try-catch

The general syntax of using try-catch is:

try

{

   //Code that needs to be checked / can create problem / exceptions

}catch(NameofException e)

{

   //Appropriate action or some message to use etc.

}

A try-catch example

The example below shows an arithmetic error occurs during the program and then how exception handling worked by using the try-catch block. The int variable was tried to divide by 0, that generates an error, see below:

Experience this online

The output will be:

Exception in thread “main” java.lang.ArithmeticException: / by zero

at test_package.exception_example.main(exception_example.java:8)

Exception handling by try-catch:

Experience this online

The output will be:

Can’t divide by 0!

Example with Java ArrayIndexOutOfBoundsException

The Java ArrayIndexOutOfBoundsException occurs as you try to access an array element that does not exist. We will handle it in try catch block; see an example below:

Experience this online

The output will be:

10

20

30

Array element does not exist  :java.lang.ArrayIndexOutOfBoundsException: 3

Using finally with try catch Java

You may want to show some message or perform some action if a program is ended, just to show things went under control. Java provides the finally keyword that is used with the try catch. The block of code inside the finally will execute as the flow of the program is out of the try-catch block.

The syntax of using Java finally keyword

try

{

//Code that needs to be checked / can create problem / exceptions

}catch(NameofException error)

{

//Appropriate action or some message to use etc.

}

finally

 

{

//The finally block always executes.

}

Example of using finally keyword

The example shows how to use the finally keyword in the try-catch block for exception handling.

Experience this online

The output will be:

10

20

30

Array element does not exist  :java.lang.ArrayIndexOutOfBoundsException: 3

The control over to finally block

Related reading:  Java.lang.nullpointerexception