Java Exceptions handling

  • 16 June 2016
  • ADM

 

Java Exceptions handling - images/logos/java.jpg

 

An exception is a problem that arises during the execution of a program or during the compilation. Based on this the exceptions can fall in one of these 2 categories:

  • Checked exceptions: A Checked exception is an exception that occurs at the compile time. Also known as compile time exceptions. These errors can't be ignored and need to be handled by the developer before compiling the code.
  • Unchecked exceptions: An Unchecked exception is an exception that occurs at the time of execution. Are also known as runtime exceptions.

Checked exceptions

For example, if you want to create a string with a specific encoding the String constructor will throw an UnsupportedEncodingException.

To handle an checked exception you have 2 options:

  • handle the error in your method, or (this fits the scenario when you are using a library and you need to handle the exceptions)
  • throw the error forward and will be treated in an upper level. (this fits the scenario when you are building a library and the library user need to handle the exceptions.)
    public static String testCheckedExceptionThrow(String param) throws UnsupportedEncodingException {
	String text = new String(param.getBytes(), "UTF8");
	return text;
    }

    public static String testCheckedExceptionHandle(String param) {
	String text = null;
	try {
	    text = new String(param.getBytes(), "UTF8");
	} catch (UnsupportedEncodingException e) {
	    text = null;
	}
	return text;
    }

Method testCheckedExceptionThrow will throw the exception forward and will need to be handled when the method is used. Method testCheckedExceptionHandle will handle the exception itself and will return null if the encoding is not supported.

Unchecked exceptions

These exceptions occur during the execution of the program and might occurs because of programming bugs, invalid data or improper usage of an API. These exceptions are ignored at during the compilation.

Catching Exceptions

To catch an exception a combination of the try and catch keywords are used. A try/catch block is placed around the code that might generate an exception. Also, multiple exceptions may occur and then multiple catch blocks can be used. If a specific code need to be executed regardless if there is any exception or not then will be placed in a finally block.

try {
   //Protected code
} catch(ExceptionType1 e1) {
   //Catch block
} catch(ExceptionType2 e2) {
   //Catch block
} catch(ExceptionType3 e3) {
   //Catch block
} finally {
   //The finally block always executes.
}

User-defined Exceptions

You can define custom exceptions for both categories checked or unchecked.

For checked exceptions Exception class is needed to be extended and for unchecked exception RuntimeException is needed to be extended.

CustomException.java - extending Exception class (checked exception)

package com.admfactory.exception;

public class CustomException extends Exception {
    
    public CustomException(String message) {
	super(message);
	System.out.println("Hello from CustomException");
    }
}

CustomRuntimeException.java - extending RuntimeException class (unchecked exception)

package com.admfactory.exception;

public class CustomRuntimeException extends RuntimeException {

    public CustomRuntimeException(String message) {
	super(message);
	System.out.println("Hello from CustomRuntimeException");
    }
}

Usage example

package com.admfactory.exception;

public class ExceptionTest {

    /**
     * Throws an checked exception if the param is null
     * 
     * @param param
     * @throws CustomException
     */
    public static void testException(String param) throws CustomException {
	if (param == null) {
	    throw new CustomException("param is null");
	}
	System.out.println("param = " + param);
    }

    /**
     * 
     * Throws an unchecked exception if the param is null
     *
     * @param param
     */
    public static void testRuntimeException(String param) {
	if (param == null) {
	    throw new CustomRuntimeException("param is null");
	}
	System.out.println("param = " + param);
    }

    public static void main(String[] args) {
	String param1 = null;
	String param2 = "TEST";

	try {
	    testException(param1);
	    testException(param2);
	} catch (CustomException e) {
	    e.printStackTrace();
	}

	testRuntimeException(param1);
	testRuntimeException(param2);
    }
}

As you can notice for checked exceptions if there are not handled (using try/catch block) there will be a compilation error.

Output

Hello from CustomException
com.admfactory.exception.CustomException: param is null
	at com.admfactory.exception.ExceptionTest.testException(ExceptionTest.java:13)
	at com.admfactory.exception.ExceptionTest.main(ExceptionTest.java:36)
Exception in thread "main" com.admfactory.exception.CustomRuntimeException: param is null
Hello from CustomRuntimeException
	at com.admfactory.exception.ExceptionTest.testRuntimeException(ExceptionTest.java:26)
	at com.admfactory.exception.ExceptionTest.main(ExceptionTest.java:42)

Checking the output it might be confusing. First 4 lines are are generated by the testException(param1); call, as the param1 is null. Second testException(param1); call will not generate any exception. Next 4 lines are generated by the testRuntimeException(param1); call, due to param1 being null. Again the second testRuntimeException(param1); will not generate any exception.

 

References