Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
27 views

Checked and Unchecked Exception in Java

Classification of Exceptions in Java

Uploaded by

jitprosen
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views

Checked and Unchecked Exception in Java

Classification of Exceptions in Java

Uploaded by

jitprosen
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

Checked and Unchecked

Exception in Java – Examples


and Differences
In this article, we will discuss the difference between two types of
exceptions viz. Checked and Unchecked Exception in Java along with the
examples. Let’s start with a detailed discussion on each of them separately.

What are Checked Exceptions in Java?


The exceptions that are checked during the compile-time are termed
as checked exceptions in Java. The Java compiler checks the checked
exceptions during compilation to verify that a method that is throwing an
exception contains the code to handle the exception with the try-catch block
or not.

And, if there is no code to handle them, then the compiler checks whether
the method is declared using the throws keyword. And, if the compiler finds
neither of the two cases, then it gives a compilation error. A checked
exception extends the Exception class.

Examples of Java Checked Exceptions


For example, if we write a program to read data from a file using a FileReader
class and if the file does not exist, then there is a FileNotFoundException.

Some checked Exceptions are


• SQLException
• IOException
• ClassNotFoundException
• InvocationTargetException
• FileNotfound Exception
Code to illustrate the checked exception:

package com.techvidvan.exceptions;
import java.io.File;
import java.io.FileReader;
public class CheckedExceptions
{
public static void main(String args[])
{
File file = new File("/home/techvidvan/file.txt");
FileReader fileReader = new FileReader(file);
System.out.println("Successful");
}
}

Output:
Exception in thread “main” java.lang.Error: Unresolved compilation problem:
Unhandled exception type FileNotFoundException
at
project1/com.techvidvan.exceptions.CheckedExceptions.main(CheckedExceptions.java:1
0)

Now, if we use the throws keyword with the main then we will not get any
error:

package com.techvidvan.exceptions;
import java.io.*;
public class CheckedExceptions
{
public static void main(String args[]) throws IOException
{
File file = new File("/home/techvidvan/file.txt");
FileReader fileReader = new FileReader(file);
System.out.println("Successful");
}
}

Output:
Successful

We can also fix the code using the try-catch block:

import java.io.*;
public class Example
{
public static void main(String args[])
{
FileInputStream fis = null;
try
{
fis = new FileInputStream("/home/techvidvan/file.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);
}
}
}

Output:
The specified file is not present at the given path
Exception in thread “main” java.lang.NullPointerException
at project1/com.techvidvan.exceptions.Example.main(Example.java:15)

What are Java Unchecked Exceptions?


An exception that occurs during the execution of a program is called an
unchecked or a runtime exception. The main cause of unchecked exceptions
is mostly due to programming errors like attempting to access an element
with an invalid index, calling the method with illegal arguments, etc.

In Java, the direct parent class of unchecked exception is RuntimeException.


Unlike the checked exceptions, the compiler generally ignores the unchecked
exceptions during compilation. Unchecked exceptions are checked during
the runtime. Therefore, the compiler does not check whether the user
program contains the code to handle them or not.
Examples of Unchecked Exceptions in Java
For example, if a program attempts to divide a number by zero. Or, when
there is an illegal arithmetic operation, this impossible event generates a
runtime exception.

Suppose, we declare an array of size 10 in a program, and try to access the


12th element of the array, or with a negative index like -5, then we get an
ArrayIndexOutOfBounds exception.

Some unchecked exceptions are:


1. ArithmeticException
2. NullPointerException
3. ArrayIndexOutOfBoundsException
4. NumberFormatException
5. InputMismatchException
6. IllegalStateException
7. MissingResourceException
8. NoSuchElementException
9. UndeclaredThrowableException
10.EmptyStackException

Code to illustrate the Unchecked Exception:

package com.techvidvan.exceptions;
public class UnCheckedExceptions
{
public static void main(String args[])
{
//ArrayIndexOutOfBoundsException
int array[] = {1, 2, 3, 4, 5};
System.out.println(array[7]);

}
}

Output:
Exception in thread “main” java.lang.ArrayIndexOutOfBoundsException: Index 7 out
of bounds for length 5
at
project1/com.techvidvan.exceptions.UnCheckedExceptions.main(UnCheckedExceptions.ja
va:8)

Note: Though the compiler does not check these exceptions, it doesn’t mean that
we shouldn’t handle them. In fact, we should handle them more carefully to
provide a safe exit.
Comparison between Checked Exceptions and Java
Unchecked Exception in Java
S.N. Checked Exception Unchecked Exception

1 Checked exceptions occur at compile time. Unchecked exceptions occur at runtime.

2 Also called Compile-time exceptions Also called Run-time exceptions

3 The compiler checks a checked exception. The compiler ignores the unchecked exceptions.

We cannot catch or handle these exceptions during


We can handle these types of exceptions during
4 the compilation because they are generated by the
compilation.
mistakes in the program.

The compiler will give an error if the code does The compiler will never give an error if the code does
5
not handle the checked exceptions. not handle the unchecked exceptions.

They are runtime exceptions and hence are not a


They are the direct subclass of the Exception
6 part of the Exception class and are the subclass of
class.
RuntimeException class

JVM needs to catch and handle the checked JVM needs not catch and handle the unchecked
7
exception. exception.

Checked exceptions are predictable erroneous Unchecked exceptions are erroneous situations
8 situations that might reasonably occur during
the proper use of an API. that mainly occur due to mistakes in programming logic.

We can create user-defined checked exceptions We can create user-defined Unchecked exceptions
9
by extending java.lang.Exception class. by extending RuntimeException class.

Examples of Checked exceptions: Examples of Unchecked Exceptions:

FileNotFoundException ArrayIndexOutOfBoundsException

NoSuchFieldException NumberFormatException

SQLException InputMismatchException
10
IOException IllegalStateException

InterruptedException ArithmeticException

NoSuchMethodException NullPointerException

ClassNotFoundException SecurityException
Exception Hierarchy
Java Exceptions are broadly divided into two parts: checked exceptions and
unchecked exceptions. The following figure shows this Exception hierarchy
in Java.

When to use Checked and Unchecked Exception in


java
According to the Oracle Java Documentation, there is a guide on when to use
checked exceptions and unchecked exceptions:

“If a client can reasonably be expected to recover from an exception, make it a


checked exception. If a client cannot do anything to recover from the exception, make
it an unchecked exception.”
For example, we can first validate the input file name before opening the file.
And if we provide the invalid name of the input, then we can throw
the checked exception.
The below code snippet shows this:

if (!isCorrectFileName(fileName))
{
throw new IncorrectFileNameException("File name is invalid: " + fileName );
}

If the input file name is an empty string, it means there is an error in the
code. In this case, we should throw an unchecked exception.

The below code snippet shows this:

if (fileName == null || fileName.isEmpty())


{
throw new NullOrEmptyException("The filename is null or empty.");
}

Summary
Exceptions in Java may hinder the normal execution of a program. There are
two kinds of exceptions in Java which are Checked or compile-time
exceptions and Unchecked or runtime exceptions. In checked exceptions, we
have to write the code to handle them otherwise the compiler gives an error.

And, in runtime exceptions, it is not necessary to write the code to handle the
exception and still, the compiler does not give any error. This article gave you
the detailed points of differences between both these exceptions in Java. You
might have understood when to use either of two exceptions.

You might also like