Java-Exception Types and Throws Statement

Exception Types

Java exceptions are divided into two categories, called checked and unchecked exceptions. All subclasses of RuntimeException class are unchecked exceptions. All other exceptions are checked exceptions.

 

Checked Exception

For checked exceptions, the compiler checks if your program handles them, either by catching them or by specifying (with a throws clause) that the method in which the exception might happen, that the method might throw that kind of exception.

Unchecked Exception

For unchecked exceptions, the compiler doesn’t do the check , so you are not required to catch them or to specify that you might throw them.

Program : Unchecked Exception

final2

 

Program : Checked Exception

final3

 

Throws Statement

Some methods are likely to generate exceptions types of checked exceptions. For example, a method that generate the exception of type InterruptedException(Checked exception). Usually, such a method will have appropriate catch blocks for handling the types of exceptions it can generate. However, such a method, instead of handling the exceptions by itself, can simply instruct the caller method to handle them.

The following program , the checkedException( ) method generate an InterruptedException object. Instead of handling this object by itself, this method instructs its caller(i.e the main() method) to handle this object. This method provides this instruction by using the throws clause in its method declaration syntax.

Program

final

Program Source

class Javaapp {
    
    static void unCheckedException()
    {
        throw new ArithmeticException();
    }
 
    public static void main(String[] args) {
     
        try{
            
            unCheckedException();
     
        }catch(ArithmeticException ex)
        { 
            System.out.println(ex);
        }
    }
}

Program Source

class Javaapp {
    
    static void checkedException() 
    {
        throw new InterruptedException();
    }
 
    public static void main(String[] args) {
     
        try{
            
            checkedException();
     
        }catch(InterruptedException ex)
        { 
            System.out.println(ex);
        }
    }
}

Program Source

class Javaapp {
    
    static void checkedException() throws InterruptedException
    {
        throw new InterruptedException();
    }
 
    public static void main(String[] args) {
     
        try{
            
            checkedException();
     
        }catch(InterruptedException ex)
        { 
            System.out.println(ex);
        }
    }
}

Leave a Comment