BeginnersBook

  • Home
  • Java
    • Java OOPs
    • Java Collections
    • Java Examples
  • C
    • C Examples
  • C++
    • C++ Examples
  • DBMS
  • Computer Network
  • Python
    • Python Examples
  • More…
    • jQuery
    • Kotlin
    • WordPress
    • SEO
    • JSON
    • JSP
    • JSTL
    • Servlet
    • MongoDB
    • XML
    • Perl

Checked and unchecked exceptions in java with examples

Last Updated: October 25, 2022 by Chaitanya Singh | Filed Under: java

There are two types of exceptions: checked exception and unchecked exception. In this guide, we will discuss them. The main difference between checked and unchecked exception is that the checked exceptions are checked at compile-time while unchecked exceptions are checked at runtime.

What are checked exceptions?

Checked exceptions are checked at compile-time. It means if a method is throwing a checked exception then it should handle the exception using try-catch block or it should declare the exception using throws keyword, otherwise the program will give a compilation error.

Lets understand this with the help of an example:

Checked Exception Example

In this example we are reading the file myfile.txt and displaying its content on the screen. In this program there are three places where a checked exception is thrown as mentioned in the comments below. FileInputStream which is used for specifying the file path and name, throws FileNotFoundException. The read() method which reads the file content throws IOException and the close() method which closes the file input stream also throws IOException.

import java.io.*;
class Example {  
   public static void main(String args[]) 
   {
	FileInputStream fis = null;
	/*This constructor FileInputStream(File filename)
	 * throws FileNotFoundException which is a checked
	 * exception
         */
        fis = new FileInputStream("B:/myfile.txt"); 
	int k; 

	/* Method read() of FileInputStream class also throws 
	 * a checked exception: IOException
         */
	while(( k = fis.read() ) != -1) 
	{ 
		System.out.print((char)k); 
	} 

	/*The method close() closes the file input stream
	 * It throws IOException*/
	fis.close(); 	
   }
}

Output:

Exception in thread "main" java.lang.Error: Unresolved compilation problems: 
Unhandled exception type FileNotFoundException
Unhandled exception type IOException
Unhandled exception type IOException

Why this compilation error? As I mentioned in the beginning that checked exceptions gets checked during compile time. Since we didn’t handled/declared the exceptions, our program gave the compilation error.
How to resolve the error? There are two ways to avoid this error. We will see both the ways one by one.

Method 1: Declare the exception using throws keyword.
As we know that all three occurrences of checked exceptions are inside main() method so one way to avoid the compilation error is: Declare the exception in the method using throws keyword. You may be thinking that our code is throwing FileNotFoundException and IOException both then why we are declaring the IOException alone. The reason is that IOException is a parent class of FileNotFoundException so it by default covers that. If you want you can declare them like this public static void main(String args[]) throws IOException, FileNotFoundException.

import java.io.*;
class Example {  
   public static void main(String args[]) throws IOException
   {
      FileInputStream fis = null;
      fis = new FileInputStream("B:/myfile.txt"); 
      int k; 

      while(( k = fis.read() ) != -1) 
      { 
	   System.out.print((char)k); 
      } 
      fis.close(); 	
   }
}

Output:
File content is displayed on the screen.

Method 2: Handle them using try-catch blocks.
The approach we have used above is not good at all. It is not the best exception handling practice. You should give meaningful message for each exception type so that it would be easy for someone to understand the error. The code should be like this:

import java.io.*;
class Example {  
   public static void main(String args[])
   {
	FileInputStream fis = null;
	try{
	    fis = new FileInputStream("B:/myfile.txt"); 
	}catch(FileNotFoundException fnfe){
            System.out.println("The specified file is not " +
			"present at the given path");
	 }
	int k; 
	try{
	    while(( k = fis.read() ) != -1) 
	    { 
		System.out.print((char)k); 
	    } 
	    fis.close(); 
	}catch(IOException ioe){
	    System.out.println("I/O error occurred: "+ioe);
	 }
   }
}

This code will run fine and will display the file content.

Here are the few other Checked Exceptions –

  • SQLException
  • IOException
  • ClassNotFoundException
  • InvocationTargetException

What are Unchecked exceptions?

Unchecked exceptions are not checked at compile time. It means if your program is throwing an unchecked exception and even if you didn’t handle/declare that exception, the program won’t give a compilation error. Most of the times these exception occurs due to the bad data provided by user during the user-program interaction. It is up to the programmer to judge the conditions in advance, that can cause such exceptions and handle them appropriately. All Unchecked exceptions are direct sub classes of RuntimeException class.

Lets understand this with an example:

Unchecked Exception Example

class Example {  
   public static void main(String args[])
   {
	int num1=10;
	int num2=0;
	/*Since I'm dividing an integer with 0
	 * it should throw ArithmeticException
         */
	int res=num1/num2;
	System.out.println(res);
   }
}

If you compile this code, it would compile successfully however when you will run it, it would throw ArithmeticException. That clearly shows that unchecked exceptions are not checked at compile-time, they occurs at runtime. Lets see another example.

class Example {  
   public static void main(String args[])
   {
	int arr[] ={1,2,3,4,5};
	/* My array has only 5 elements but we are trying to 
         * display the value of 8th element. It should throw
	 * ArrayIndexOutOfBoundsException
         */
	System.out.println(arr[7]);
   }
}

This code would also compile successfully since ArrayIndexOutOfBoundsException is also an unchecked exception.
Note: It doesn’t mean that compiler is not checking these exceptions so we shouldn’t handle them. In fact we should handle them more carefully. For e.g. In the above example there should be a exception message to user that they are trying to display a value which doesn’t exist in array so that user would be able to correct the issue.

class Example {  
   public static void main(String args[]) {
	try{
	   int arr[] ={1,2,3,4,5};
	   System.out.println(arr[7]);
	}
        catch(ArrayIndexOutOfBoundsException e){
	   System.out.println("The specified index does not exist " +
		"in array. Please correct the error.");
	}
   }
}

Output:

The specified index does not exist in array. Please correct the error.

Here are the few unchecked exception classes:

  • NullPointerException
  • ArrayIndexOutOfBoundsException
  • ArithmeticException
  • IllegalArgumentException
  • NumberFormatException
❮ PreviousNext ❯

Top Related Articles:

  1. Constructor Overloading in Java with examples
  2. TreeMap in Java with Example
  3. Method overriding in java with example
  4. Java Exception Handling Examples
  5. How to create a File in Java

Tags: Exception-Handling

About the Author

I have 15 years of experience in the IT industry, working with renowned multinational corporations. Additionally, I have dedicated over a decade to teaching, allowing me to refine my skills in delivering information in a simple and easily understandable manner.

– Chaitanya

Comments

  1. Gayathri says

    October 7, 2014 at 2:52 PM

    stil am not clear., y in the 1st example der is an error., and y in next 2 examples there is no error? can anybdy clear my doubt?

    Reply
    • hardik says

      December 15, 2014 at 9:54 AM

      In the first example, we are not handling the exception thats why it will throw compilation error(public static void main(String args[]) whereas in other two examples exceptions are being handled properly(public static void main(String args[]) throws IOException).

      Reply
      • Shreyas says

        February 2, 2015 at 12:20 PM

        Hardik, doesn’t make sense.

        If the file doesn’t ever exist, how will that display file content on the screen suddenly irrespective of handling?

        Reply
        • Subrat Mainali says

          August 4, 2016 at 6:32 AM

          Hardik makes sense. Java REQUIRES you to check checked exceptions. We are getting the error BECAUSE we didn’t check the checked exceptions.

          Reply
        • Kaushal says

          April 4, 2018 at 7:32 AM

          Hi Shreyas,

          The error does not mean that the file is actually not present but the compiler reminds us that there may be a possibility that the file may be missing and we get an exception so it is better you handle this exception and in next two programs, if the file is available, we will get the content and if not then it will just print the exception details and will continue the execution of the program.

          Reply
      • voldemort says

        September 27, 2015 at 8:27 AM

        Thank you so much for detailed explanation.

        Reply
    • Daryll David says

      April 7, 2015 at 2:28 PM

      Using classes that opens a particular file lets you EXPLICITLY invoke throws those Exceptions or use try and catch block. Because when you compile(checked exception), Java checks to see if the file exists at the specified path. It doesn’t check at run-time(Unchecked exception).

      Reply
  2. Renu Mishra says

    January 12, 2015 at 8:02 AM

    hi, may i know the code explanation please while(( k = fis.read() ) != -1)
    Waiting for your response.

    Reply
    • Imran says

      March 24, 2015 at 12:14 PM

      Read is a method which is non static so we are calling it with an object fis . That method will return some value which will be stored in field or variable k, now the k value is compared with -1 with (!=) not equal to symbol . While k is not equal to -1 the loop will continue ! I hope u got it right..

      Reply
    • Cvani says

      April 25, 2015 at 5:10 PM

      read() belongs to FileInputStream class, which is used to read a file.
      fis.read() will return int value i.e. the ASCII value of that integer.
      As ASCII starts from 0 to 255 , hence we provide the first negative integer of the number system i.e -1 .
      Hence it will read all the character of the file .

      Reply
  3. ashish sharma says

    June 4, 2015 at 8:07 AM

    superb explanation thanks.

    Reply
  4. sirisha says

    June 25, 2015 at 5:55 AM

    thank u so much now im clear in exception handling.super explanation.

    Reply
  5. Ruchi says

    October 7, 2015 at 9:41 PM

    Can throws keyword be used to handle Unchecked exception? Or Unchecked Exception can be handled only with try-catch blocks.

    Reply
  6. Prakash says

    January 5, 2016 at 3:51 AM

    how can we handle the unchecked exception?

    Reply
  7. Poulami Biswas says

    January 21, 2016 at 5:45 PM

    Hi, you have mentioned that DataAccessException is a checked exception. However it is a runtime exception and that’s what makes it different from SQLException.

    Reply
  8. Vineet says

    July 4, 2016 at 7:30 PM

    Excellent explanations and Examples used, in few seconds got everything. Great job.
    Thanks

    Reply
  9. Gopal Panwar says

    July 30, 2016 at 5:50 AM

    Fantastic Explanations and perfect examples used.

    I also want to ask is Can we handle the unchecked exceptions only via try-catch block?

    Is there any other way…

    Reply
  10. Gourav says

    August 1, 2016 at 7:46 AM

    what will happen if we only add throws for checked exception and do not handle it ?will it still give compile error?

    Reply
    • Rajiv says

      June 20, 2017 at 11:13 PM

      It handles it automatically on writing “throws IOException”. No error will come at compile time. Then, you may get Unchecked Exception at run time if there is any logical error

      Reply
  11. Arjun says

    July 25, 2017 at 11:45 PM

    When We should handle the exception and when should We throws the exception ? Please try to give explanation in a simple way. Your help is much appreciated.
    Thanks in advance :)

    Reply
    • Chaitanya Singh says

      September 6, 2017 at 4:48 PM

      Hey Arjun, refer this guide, this will answer your question.

      Reply

Leave a Reply Cancel reply

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

Java Tutorial

Java Introduction

  • Java Index
  • Java Introduction
  • History of Java
  • Features of Java
  • C++ vs Java
  • JDK vs JRE vs JVM
  • JVM - Java Virtual Machine
  • First Java Program
  • Variables
  • Data Types
  • Operators

Java Flow Control

  • Java If-else
  • Java Switch-Case
  • Java For loop
  • Java while loop
  • Java do-while loop
  • Continue statement
  • break statement

Java Arrays

  • Java Arrays

OOPs Concepts

  • OOPs Concepts
  • Constructor
  • Java String
  • Static keyword
  • Inheritance
  • Types of inheritance
  • Aggregation
  • Association
  • Super Keyword
  • Method overloading
  • Method overriding
  • Overloading vs Overriding
  • Polymorphism
  • Types of polymorphism
  • Static and dynamic binding
  • Abstract class and methods
  • Interface
  • Abstract class vs interface
  • Encapsulation
  • Packages
  • Access modifiers
  • Garbage Collection
  • Inner classes
  • Static import
  • Static constructor

Java Exception Handling

  • Exception handling
  • Java try-catch
  • Java throw
  • Java throws
  • Checked and Unchecked Exceptions
  • Jav try catch finally
  • Exception Examples
  • Exception Propagation

Collections Framework

  • Collections in Java
  • Java ArrayList
  • Java LinkedList
  • Java Vector
  • Java HashSet
  • Java LinkedHashSet
  • Java TreeSet
  • Java HashMap
  • Java TreeMap
  • Java LinkedHashMap
  • Java Queue
  • Java PriorityQueue
  • Java Deque
  • Comparable interface
  • Comparator interface
  • Collections Interview Questions

MORE ...

  • Java Scanner Class
  • Java 8 Features
  • Java 9 Features
  • Java Conversion
  • Java Date
  • Java Multithreading
  • Java I/O
  • Java Serialization
  • Java Regex
  • Java AWT
  • Java Swing
  • Java Enum
  • Java Annotations
  • Java main method
  • Java Interview Q

Copyright © 2012 – 2025 BeginnersBook . Privacy Policy . Sitemap