Register Now

Login

Lost Password

Enter your email to reset your password.

BY Author

Checked Exceptions

The exception types that are checked by JVM at compile time are known as checked exceptions.

These exceptions are checked by JVM at compile time because they are more likely to occur during execution of the program.

Example, suppose we want to do an operation with some specific file, then there is a chance that specific file may or may not be present at the required location. Therefore there is a more chance of generating exceptions related to file like FileNotFoundException, etc.

Therefore Java considers that it is more important to check such type of exceptions at compile time.

Since these types of exceptions are checked at compile time, they are known as checked exception.

To avoid compile time error while using checked exception, they must be handled by using try-catch clause or must be declared at the method or constructor header with throws keyword.

Note

It is better to handle checked exception using try-catch block instead of throws keyword.

 

Unchecked exceptions

The exception that is not checked by JVM at compile time is known as the unchecked exception.

These exceptions are not checked because they may occur rarely and JVM can’t guess about them.

 

The throws keyword

If the program or a part of the program is more prone to generate checked exception, then we must use try-catch block or throws keyword.

The throws keyword can be used with only methods & constructors.

The checked exception is declared at method header or constructor header with throws keyword.

Note

The throws keyword does not handle the exception, but it just tells to JVM that programmer is aware of those declared checked exceptions.

Example

import java.io.File;

class ThrowsDemo 
{
    public static void main(String args[])
    {
        File f = new File("XYZ");
        f.createNewFile();
    }
}

Output

Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Unhandled exception type IOException
at throws_keyword.ThrowsDemo.main(ThrowsDemo.java:8)

This program will show compile time error because there is no any way to handle checked exception, IOException.

To prevent this compile time error, we must use throws declaration or surround line,

f.createNewFile();

with a try-catch block.

Let’s try above program using throws declaration

import java.io.IOException;

class ThrowsDemo 
{
    public static void main(String args[]) throws IOException
    {
        File f = new File("XYZ");
        f.createNewFile();
        System.out.println("File created successfully");
    }
}

Output

File created successfully

 

Leave a reply