Tutorials Hut

Java Exceptions

Java exception is an event which is created when code is not able to complete normally, it is an error situation which a programmer can handle while writing the code but this may occur at run time of program as well.

As the name suggests exception which literally means something which is not normal and hence exception, a simple example can be if we divide an integer value by zero in mathematics the result is infinite or can’t be determined and so it is an mathematically exception and same thing and many more is handled in java using java exceptions.

Java Exceptions Type

In java to handle such cases where an unexpected event happens in code we have 3 categories of exception.

  1. Checked Exception or Compile Time Exception
  2. Unchecked Exception or Runtime Exception
  3. Errors

Java Checked Exception

Checked exceptions can be observed while compiling any java code, java compiler can determine based on used java classes if there will be an exception or not and we have to handle those exceptions or throw them to parent or caller.

Few checked exceptions are: FileNotFoundException, IOException, SQLException etc.

Example Of Checked Exception:

import java.io.File;
import java.io.FileReader;
public class ExceptionExample {
public static void main(String[] args) {
File file = new File("test.txt");
FileReader fileReader = new FileReader(file);
}
}

Output While Compiling:

ExceptionExample.java:9: error: unreported exception FileNotFoundException; must be caught or declared to be thrown
FileReader fileReader = new FileReader(file);
^
1 error

Java Unchecked Exception

Unchecked exceptions or runtime exceptions are those exceptions which occur when we execute or run java programs. The reason they are called unchecked is because java compilers can’t check them while compiling, it is not like checked exceptions.

Few examples of run time exceptions are NullPointerException, ArrayIndexOutOfBoundsExceptionexception, InvalidArgumentException and etc.

Example

import java.util.List;
public class ExceptionExample {
public static void main(String[] args) {
List strList = null;
strList.add("item1");
}
}

Output:

Exception in thread "main" java.lang.NullPointerException
at ExceptionExample.main(ExceptionExample.java:10)

Java Errors

If due to some event running JVM is not able to work properly then that event will be called an error, error is not an exception and can’t be handled, we may try to code in such a way that error never comes but still they may come.

To understand let’s say in a running java program we are creating some heavy objects in a loop and JVM is not able to claim memory and getting full, this may cause out of memory error java.lang.OutOfMemoryError.

Example: Below code is designed in such a way that it will result in JVM memory getting full and throwing this error java.lang.OutOfMemoryError, please note this is not guaranteed because it depends on initial memory assigned to JVM etc.

public class ExceptionExample {
public static void main(String[] args) {
while(true) {
String[][][][] strArray = new String[5000][5000][5000][5000];
}
}
}
Production code

Output:

Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at ExceptionExample.main(ExceptionExample.java:11)

Exception Hierarchy

Below diagrams shows hierarchy of exceptions, throwable is at the top then it divides into errors and exceptions and then exceptions divide into checked and unchecked exceptions.

Diagram of exception hierarchy:

Java Exceptions

Exception Class Methods

Below are few useful methods in Exception class:

  1. getMessage() – This method returns a String and message from an exception object.
  2. getCause() – This method returns a cause wrapped in Throwable objects.
  3. toString() – Converts into string.
  4. printStackTrace() – This method prints jvm stack trace of exception, you can check at which line and what caused exception.
  5. getStackTrace() – Returns array where each element contains stack trace.
  6. fillInStackTrace() – Fills tacktrace.

Exception Handling

To handle checked or compile time exception there are two approaches:

  1. Catch Exception – In this approach wherever we see exceptions may occur we can add try and catch blocks to catch them, we will see details in next section.
  2. Throw/Throws– This is a second approach where we may simply throw an exception from a method where it is coming and let the next class or JVM handle it, this may lead to errors if not handled later.

Some of you may think what about unchecked exceptions or errors? normally programmers are just careful about them and create logic in such a way that it never occurs.

Try Catch

Try catch block is a way to handle exceptions in java by catching the exception and then taking appropriate measures.
In the try block of code we write normal code and if there is an exception code will leave the execution and go to the catch block where we take action based on the exception.

Simple Syntax For Try Catch:

try {
//Some code which may throw exception
}
catch(Exception ex) {
//here we catch exceptions and do some logging or any other logic.
}

Example:

Below code throws FileNotFound exception and it is handled by try and catch block:

import java.io.File;

import java.io.FileNotFoundException;

import java.io.FileReader;



public class ExceptionExample {



	public static void main(String[] args) {

    	try {

        	System.out.println("we are in try block doing some file read operation which may throw file not found exception");

        	File file = new File("test.txt");

        	FileReader fileReader = new FileReader(file);

    	}

    	catch (FileNotFoundException ex) {

        	System.out.println("we are in catch block going to print stackTrace");

        	ex.printStackTrace();

    	}

	}

}

Output:
we are in try block doing some file read operation which may throw file not found exception
we are in catch block going to print stackTrace.

java.io.FileNotFoundException: test.txt (No such file or directory)
        	at java.io.FileInputStream.open0(Native Method)
        	at java.io.FileInputStream.open(FileInputStream.java:195)
        	at java.io.FileInputStream.(FileInputStream.java:138)
at java.io.FileReader.(FileReader.java:72)
at ExceptionExample.main(ExceptionExample.java:11) at java.io.FileReader.(FileReader.java:72)
at ExceptionExample.main(ExceptionExample.java:11) at ExceptionExample.main(ExceptionExample.java:11)

Try with Multiple Catch

If a block of code may throw multiple types of exceptions we can add more than one catch block, so there can be only one try and multiple catch blocks.

Syntax For Try and Multiple Catch:

try {

 //Some code which may throw exception

}

catch(ExceptionType ex) {

//here we catch exceptions and do some logging or any other logic.

}

catch(ExceptionType2 ex) {

//here we catch exceptions and do some logging or any other logic.

}

…….

Example:
Below code has two catch blocks one for FileNouFountException and second IOException.

import java.io.FileNotFoundException;

import java.io.FileReader;

import java.io.IOException;



public class ExceptionExample {



	public static void main(String[] args) {

    	try {

        	System.out.println("we are in try block doing some file read operation which may throw file not found exception");

        	File file = new File("test.txt");

        	FileReader fileReader = new FileReader(file);

        	fileReader.read();

    	}

    	catch (FileNotFoundException ex) {

            System.out.println("we are in catch block FileNotFoundException");

        	ex.printStackTrace();

    	} catch (IOException e) {

        	System.out.println("we are in catch block IOException");

        	e.printStackTrace();

    	}

	}

}

Throws and Throw

This is the second approach to handle exceptions where we throw the exception and the method which throws will use throws keyword and type of exception to throw it.

Example:
Below example instead of using catch we have used throws keyword with method main and throwing FileNotFoundException to parent caller and hence caller of method is responsible to handle.

import java.io.File;

import java.io.FileNotFoundException;

import java.io.FileReader;



public class ExceptionExample {



	public static void main(String[] args) throws FileNotFoundException {



    	System.out.println("we are in try block doing some file read operation which may throw file not found exception");

    	File file = new File("test.txt");

    	FileReader fileReader = new FileReader(file);



	}

}

Throw: Throw keyword is used in any method when we want to throw some exception or custom exception.

This helps developers to throw some standard or custom exceptions.

Example:
Below is an example of throw exception class.

import java.io.FileNotFoundException;



public class ExceptionExample {



	public static void main(String[] args) throws FileNotFoundException {



    	System.out.println("We are throwing exception using throw key word, parent or caller need to haled this.");

    	throw new FileNotFoundException("In main file test.txt not found");



	}

}

Output:

We are throwing exception using throw key word, parent or caller need to haled this.
Exception in thread “main” java.io.FileNotFoundException: In main file test.txt not found
at ExceptionExample.main(ExceptionExample.java:8)

Java Custom Exception

We can develop our own exception by extending existing exception classes.
Custom exception classes will be child of any main exception class. Simple example can be if you have a application which takes different currency names and processes and in case when a currency is unknown code may throw “currency not found exception” this will be custom exception.
In below example we will create our custom currency exception class

Example:

In below code we have a user defined exception class CurrencyNotFoundException and it throws exception if you call processMyCurrency() method and supply “unknown” currency.

import java.io.FileNotFoundException;

public class ExceptionExample {

public static void main(String[] args) throws FileNotFoundException, CurrencyNotFoundException {

     CurrencyNotFoundException currencyNotFoundException = new CurrencyNotFoundException();

     String currency1 = currencyNotFoundException.processMyCurrency("USD");

     System.out.println("processed USD and msg is:"+currency1);

     String currency2 = currencyNotFoundException.processMyCurrency("unknown");

     System.out.println("processed unknown and msg is:"+currency2);

}

}

//Our user defined or custom exception class

class CurrencyNotFoundException extends Exception {

String processMyCurrency(String currencyName) throws CurrencyNotFoundException {

     if (currencyName.equals("unknown")) {

         throw new CurrencyNotFoundException();

     }

     return "ok "+currencyName;

}

}

Output

processed USD and msg is:ok USD
Exception in thread "main" CurrencyNotFoundException
        	at CurrencyNotFoundException.processMyCurrency(ExceptionExample.java:20)
        	at ExceptionExample.main(ExceptionExample.java:9)

Advantage of Exceptions

Below are advantages of exceptions:

1) Exception handling features of java separates normal code from code which may throw exceptions.

2) Safety against code which is prone to throw exception.

3) Propagates exception to calling methods.

4) Grouping of different types of exception for example IOException call will have all IO operations related exceptions.

References

Reference page on java exception from oracle: Java Exceptions

Next Article To Read

If you missed our previous article on Java Files may explore that, here is next article you may explore:


















  • Leave a Reply

    Your email address will not be published. Required fields are marked *