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.
- IOException
- SQLException
- DataAccessException
- ClassNotFoundException
- InvocationTargetException
- 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.
- Modify lines 16 and 20 and adds
throws IOException
- 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:
- NullPointerException
- ArrayIndexOutOfBound
- IllegalArgumentException
- IllegalStateException
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.
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); } }
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.