0% found this document useful (0 votes)
43 views

In Java, Exception Can Be Checked or Unchecked. They Both Fit Into A Class Hierarchy. The Following Diagram Shows Java Exception Classes Hierarchy

In Java, exceptions can be checked or unchecked. Checked exceptions are verified at compile-time and must be declared using a try-catch block or throws keyword, otherwise compilation will fail. Unchecked exceptions are verified at runtime and do not require handling at compile-time. Common checked exceptions include FileNotFoundException and IOException, while common unchecked exceptions are NullPointerException and ArrayIndexOutOfBoundsException. The document provides examples demonstrating how to handle checked and unchecked exceptions in Java code.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
43 views

In Java, Exception Can Be Checked or Unchecked. They Both Fit Into A Class Hierarchy. The Following Diagram Shows Java Exception Classes Hierarchy

In Java, exceptions can be checked or unchecked. Checked exceptions are verified at compile-time and must be declared using a try-catch block or throws keyword, otherwise compilation will fail. Unchecked exceptions are verified at runtime and do not require handling at compile-time. Common checked exceptions include FileNotFoundException and IOException, while common unchecked exceptions are NullPointerException and ArrayIndexOutOfBoundsException. The document provides examples demonstrating how to handle checked and unchecked exceptions in Java code.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

Exception handling in Java

In Java, exception can be checked or unchecked. They both fit into a class hierarchy. The
following diagram shows Java Exception classes hierarchy.
The rationale behind the hierarchy is as follows:

 Exception subclasses represent errors that a program can reasonably recover from.
Except for RuntimeException and its subclasses (see below), they generally represent
errors that a program will expect to occur in the normal course of duty: for example,
network connection errors and filing system errors.
 Error subclasses represent "serious" errors that a program generally shouldn't expect to
catch and recover from. These include conditions such as an expected class file being
missing, or an OutOfMemoryError.
 RuntimeException is a further subclass of Exception. RuntimeException and its
subclasses are slightly different: they represent exceptions that a program shouldn't
generally expect to occur, but could potentially recover from. They represent what are
likely to be programming errors rather than errors due to invalid user input or a badly
configured environment.

 Checked and unchecked exceptions in


java with examples
 There are two types of exceptions: checked exceptions and unchecked exceptions. In this
tutorial we will learn both of them with the help of examples. 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. It is
named as checked exception because these exceptions are checked at Compile time.

Lets understand this with this 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 an 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[])
{
FileInputStreamfis = 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?

import java.io.*;
classExample{
publicstaticvoid main(Stringargs[])
{
FileInputStreamfis=null;
try{
fis=newFileInputStream("B:/myfile.txt");
}catch(FileNotFoundExceptionfnfe){
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(IOExceptionioe){
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
 DataAccessException
 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.

class Example {
public static void main(String args[])
{
intarr[] ={1,2,3,4,5};
/*My array has only 5 elements but
* I'm 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.

class Example {
public static void main(String args[])
{
try{
intarr[] ={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.");
}
}
}

Here are the few most frequently seen unchecked exceptions –

 NullPointerException
 ArrayIndexOutOfBoundsException
 ArithmeticException
 IllegalArgumentException

You might also like