Better Understanding on Checked Vs. Unchecked Exceptions – How to Handle Exception Better Way in Java?

Last updated
App Shah
Crunchify » Java and J2EE Tutorials » Better Understanding on Checked Vs. Unchecked Exceptions – How to Handle Exception Better Way in Java?

Java Checked Exception by Crunchify

Checked Exception

What is Checked Exception in Java Programming language. In simple language: Exception which are checked at Compile time called Checked Exception. Some these are mentioned below. If in your code if some of method throws a checked exception, then the method must either handle the exception or it must specify the exception using throws keyword.

  1. IOException
  2. SQLException
  3. DataAccessException
  4. ClassNotFoundException
  5. InvocationTargetException
  6. MalformedURLException

Let’s take a look at example:

In below example we are going to get contents of site “crunchify.com” and print it in console. During this operation, Java Program will throw MalformedURLException or IOException at below highlighted lines.

package com.crunchify.tutorial;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;

/**
 * @author crunchify.com
 * 
 */

public class CrunchifyCheckedException {
	public static void main(String[] args) {
		System.out.println("\nOutput: \n" + callCrunchifyURL("https://crunchify.com"));
	}

	public static String callCrunchifyURL(String myURL) {
		System.out.println("Requested URL:" + myURL);
		StringBuilder sb = new StringBuilder();
		URLConnection urlConn = null;
		InputStreamReader in = null;

		URL url = new URL(myURL);
		urlConn = url.openConnection();
		if (urlConn != null)
			urlConn.setReadTimeout(60 * 1000);
		if (urlConn != null && urlConn.getInputStream() != null) {
			in = new InputStreamReader(urlConn.getInputStream(), Charset.defaultCharset());
			BufferedReader bufferedReader = new BufferedReader(in);
			if (bufferedReader != null) {
				int cp;
				while ((cp = bufferedReader.read()) != -1) {
					sb.append((char) cp);
				}
				bufferedReader.close();
			}
		}
		in.close();
		return sb.toString();
	}
}

There are two ways to solve this. Add throws clause OR Add Try, Catch block to your code to solve it. Here is an updated code.

  1. Modify lines 16 and 20 and adds throws IOException
  2. Add try catch block on 26,42,43
package com.crunchify.tutorial;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;

/**
 * @author crunchify.com
 * 
 */

public class CrunchifyCheckedException {
	public static void main(String[] args) throws IOException {
		System.out.println("\nOutput: \n" + callCrunchifyURL("https://crunchify.com"));
	}

	public static String callCrunchifyURL(String myURL) throws IOException {
		System.out.println("Requested URL:" + myURL);
		StringBuilder sb = new StringBuilder();
		URLConnection urlConn = null;
		InputStreamReader in = null;

		try {
			URL url = new URL(myURL);
			urlConn = url.openConnection();
			if (urlConn != null)
				urlConn.setReadTimeout(60 * 1000);
			if (urlConn != null && urlConn.getInputStream() != null) {
				in = new InputStreamReader(urlConn.getInputStream(), Charset.defaultCharset());
				BufferedReader bufferedReader = new BufferedReader(in);
				if (bufferedReader != null) {
					int cp;
					while ((cp = bufferedReader.read()) != -1) {
						sb.append((char) cp);
					}
					bufferedReader.close();
				}
			}
		} catch (IOException e) {
                // TODO:  Consume and Throw an error with detailed message.
		}
		in.close();
		return sb.toString();
	}
}

Unchecked Exception

Unchecked Exception in Java is those Exceptions whose handling is NOT verified during Compile time. These exceptions occurs because of bad programming.

The program won’t give a compilation error.

All Unchecked exceptions are direct subclasses of RuntimeException class.

Simple Example: You have created online form which accepts user input. It’s free text form. Use may enter any wrong value in case of email field, or user name field OR phone number field.

If you don’t have validation at client side then there are more possibilities to get Runtime Validation Exception while running application in production. Error may throw by DB operation or converting field from one format to another.

Below are type of Unchecked Exceptions:

The one most annoys me is NullPointer Exception. I’ve written a detailed article on NPE last week.

There are total 8 different tips provided to avoid NPE.

Java Checked Vs Unchecked Exception - Crunchify

package com.crunchify.tutorial;

/**
 * @author crunchify.com
 */

public class CrunchifyUncheckedException {
	public static void main(String args[]) {
		String crunchifyArr[] = { "Crunchify", "Google", "Yahoo", "Amazon", "eBay" };
		String myString = crunchifyArr[7]; // This throws ArrayIndexOutOfBoundException
		System.out.println(myString);
	}
}

ArrayIndexOutofBoundException - Crunchify Tips

package com.crunchify.tutorial;

/**
 * @author crunchify.com
 */

public class CrunchifyUncheckedException {
	public static void main(String args[]) {
		String crunchifyArr[] = { "Crunchify", "Google", "Yahoo", "Amazon", "eBay" };
		try {
			String myString = crunchifyArr[7]; // This throws ArrayIndexOutOfBoundException
			System.out.println(myString);
		} catch (ArrayIndexOutOfBoundsException e) {
			System.out.println("ArrayIndexOutOfBoundException appears here. Better handle it in code above :)" + e);
		}
	}
}

In Java 7, you could handle multiple Exceptions in single Catch block. You could change line 13 from above line changed to below.

} catch (ArrayIndexOutOfBoundsException | NumberFormatException e) {

As a summary, Both Checked and Unchecked Exception are handled using keyword try, catch and finally.

In terms of Functionality Checked and Unchecked Exception are the same.

10 thoughts on “Better Understanding on Checked Vs. Unchecked Exceptions – How to Handle Exception Better Way in Java?”

  1. Checked Exceptions should be used to declare expected errors from which there are chances to recover from. It doesn’t make sense telling callers to anticipate exceptions that they cannot recover from.

    RunTime and Checked exceptions are functionally equivalent, whatever handling or recovery checked exceptions can do, runtime exceptions can also do. For checked exceptions it has been made sure (forced) that handling is there by making it a compile time error.

    Reply

Leave a Comment