Exceptions

Exceptions in java are any abnormal, unexpected events or extraordinary conditions that may occur at compile or at runtime. They could be file not found exception, unable to get connection exception and so on. On such conditions java throws an exception object. Java Exceptions are basically Java objects. No Project can never escape a java error exception.

Java exception handling is used to handle error conditions in a program systematically by taking the necessary action. Exception handlers can be written to catch a specific exception such as Number Format exception, or an entire group of exceptions by using a generic exception handlers. Any exceptions not specifically handled within a Java program are caught by the Java run time environment.

An exception is a subclass of the Exception class. Exception and Error classes, are subclasses of the Throwable class.

Java exceptions are raised with the throw keyword and handled within a catch block

Throwable Class

The Throwable class provides a String variable that can be set by the subclasses to provide a detail message that provides more information of the exception occurred. All classes of throwables define a one-parameter constructor that takes a string as the detail message.

The class Throwable provides getMessage() function to retrieve an exception. It has a printStackTrace() method to print the stack trace to the standard error stream. Lastly it also has a toString() method to print a short description of the exception. For more information on what is printed when the following messages are invoked, please refer the java docs.

Syntax

String getMessage()        Returns the detail message string of this throwable (which may be null). 

void printStackTrace()    Prints this throwable and its backtrace to the standard error stream

      A typical example:

 1 class MyClass {
 2     public static void main(String[] args) {
 3         crunch(null);
 4     }
 5     static void crunch(int[] a) {
 6         mash(a);
 7     }
 8     static void mash(int[] b) {
 9         System.out.println(b[0]);
10     }
11 }



produces
Exception in thread "main" java.lang.NullPointerException
at MyClass.mash(MyClass.java:9)
at MyClass.crunch(MyClass.java:6)
at MyClass.main(MyClass.java:3)

Class Error

Errors are irrecoverable condtions that can never be caught. Example: Memory leak, LinkageError etc. Errors are direct subclass of Throwable class.

Class Exception

The class Exception represents exceptions that a program faces due to abnormal or special conditions during execution. Exceptions can be of 2 types: Checked (Compile time Exceptions)/ Unchecked (Run time Exceptions).

Class RuntimeException

Runtime exceptions represent programming errors that manifest at runtime. For example ArrayIndexOutOfBounds, NullPointerException and so on are all subclasses of the java.lang.RuntimeException class, which is a subclass of the Exception class. These are basically business logic programming errors.

Checked and Unchecked Exceptions

Checked exceptions are subclass’s of Exception excluding class RuntimeException and its subclasses. Checked Exceptions forces programmers to deal with the exception that may be thrown.  When a checked exception occurs in a method, the method must either catch the exception and take the appropriate action, or pass the exception on to its caller

Unchecked exceptions are RuntimeException and any of its subclasses. Class Error and its subclasses also are unchecked. Unchecked exceptions , however, the compiler doesn’t force the programmers to either catch the exception or declare it in a throws clause. In fact, the programmers may not even know that the exception could be thrown. Example: ArrayIndexOutOfBounds Exception. They are either irrecoverable (Errors) and the program should not attempt to deal with them, or they are logical programming errors. (Runtime Exceptions). Checked exceptions must be caught at compile time. Runtime exceptions do not need to be. Errors often cannot be.

Exception Statement Syntax

Exceptions are handled using a try-catch-finally construct, which has the Syntax

try {
    <code>
} catch (<exception type1> <parameter1>) {
      // 0 or more <statements>
}
} finally { // finally block
<statements>
}

try Block
The java code that you think may produce an exception is placed within a try block for a suitable catch block to handle the error.

If no exception occurs the execution proceeds with the finally block else it will look for the matching catch block to handle the error. Again if the matching catch handler is not found execution proceeds with the finally block and the default exception handler throws an exception.. If an exception is generated within the try block, the remaining statements in the try block are not executed.

catch Block
Exceptions thrown during execution of the try block can be caught and handled in a catch block. On exit from a catch block, normal execution continues and the finally block is executed (Though the catch block throws an exception).

finally Block
A finally block is always executed, regardless of the cause of exit from the try block, or whether any catch block was executed. Generally finally block is used for freeing resources, cleaning up, closing connections etc. If the finally clock executes a control transfer statement such as a return or a break statement, then this control statement determines how the execution will proceed regardless of any return or control statement present in the try or catch.


Some predefined Exceptions:

Exception

    ClassNotFoundException

    IllegalAccessException

    InterrupredException

    NoSuchMethodException

    RuntimeException

        ArithmeticException

        ArrayStoreException

        ClassCastException

        NegativeArraysizeException

        NullPointerException

        SecurityException

        IndexOutOfBoundsException

        String IndexOutOfBoundsException

        Array IndexOutOfBoundsException

        IllegalArgumentException

        NumberFormatException

        IllegalThreadStateException 

Rules for try, catch and finally Blocks

1. For each try block there can be zero or more catch blocks, but only one finally block. 

2. The catch blocks and finally block must always appear in conjunction with a try block.

3. A try block must be followed by either at least one catch block or one finally block.

4. The order exception handlers in the catch block must be from the most specific exception


 

Example 1: Addition  of 2 int numbers - without exception catch
 
import java.util.Scanner;

public class Sum {
    public static void main(String[] arg) {
        Scanner in = new Scanner(System.in);
        int first,second;
        String rez;
        System.out.println ("Addition of two integers\n");
        System.out.print("please input the first integer: ");
        first = getInt(in);
        System.out.print("please input the second integer: ");
        second = getInt(in);
        rez="\nthe sum of "+first+" and "+second+" is: "+(first+second);
        System.out.println(rez);
    }
    public static int getInt(Scanner in) {    
        return Integer.parseInt(in.nextLine());
    }

}

Example 2Addition of 2 int numbers - with exception catch   

import java.util.Scanner;

public class SumExc {
    public static void main(String[] arg) {
        Scanner in = new Scanner(System.in);
        int first=0,second=0;
        String rez="";
        System.out.println ("Addition of two integers\n");
        try {
            System.out.print("please input the first integer: ");
            first = getInt(in);        
            System.out.print("please input the second integer: ");
            second = getInt(in);
            rez="\nthe sum of "+first+" and "+second+" is: "+(first+second);
        }
        catch(java.lang.NumberFormatException e1) {
            rez="Both must be integers! The program terminated!";
        }
        finally {
            System.out.println(rez);
        }

    }
    public static int getInt(Scanner in) {  
// no catch in the method
        return Integer.parseInt(in.nextLine());
    }

}

 
Defining new EXCEPTIONS!!
We can have our own custom Exception handler to deal with special exception conditions instead of using existing exception classes. Custom exceptions usually extend the Exception class directly or any subclass of Exception (making it checked).
The super() call can be used to set a detail message in the throwable.


throw, throws statement

A program can explicitly throw an exception using the throw statement besides the implicit exception thrown.

The general format of the throw statement is as follows:

throw <exception reference>;

The Exception reference must be of type Throwable class or one of its subclasses. A detail message can be passed to the constructor when the exception object is created.

throw new TemperatureException(”Too hot”);

A throws clause can be used in the method prototype.

Method() throws <ExceptionType1>,…, <ExceptionTypen> {

}

Each <ExceptionTypei> can be a checked or unchecked or sometimes even a custom Exception. The exception type specified in the throws clause in the method prototype can be a super class type of the actual exceptions thrown. Also an overriding method cannot allow more checked exceptions in its throws clause than the inherited method does.

When an exception is thrown, normal execution is suspended. The runtime system proceeds to find a matching catch block that can handle the exception. Any associated finally block of a try block encountered along the search path is executed. If no handler is found, then the exception is dealt with by the default exception handler at the top level. If a handler is found, execution resumes with the code in its catch block. Below is two examples to show the use of a throws and a throw statement.

Example 4 (catch in the function):

import java.util.*;
class NoNote extends Exception{
    String message;
    NoNote(String message){
        this.message = message;
        System.out.println(message);
    }
}
public class Exc4 {
    public static void main(String arg[]){
        System.out.println("Note: "+Note());
    }
    static int Note(){
        Scanner sc = new Scanner(System.in);
        boolean ok;
        int note;
        do{
            ok = true;
            System.out.print("next note:");
            note = sc.nextInt();
            try{
                if((note>6)||(note <2)){
                    throw new NoNote("outside [2,6]");
                }
            }
            catch(NoNote ex){
                ok = false;
            }
        }while(!ok);
        return note;
    }
}

 

Example 5 (catch outside the  function ):
class NoNote extends Exception{
    String message;
    NoNote(String message){
        this.message = message;
        System.out.println(message);
    }
}
import java.util.*;
public class Exc4 {
    static Scanner sc=new Scanner(System.in);
    public static void main(String arg[]){
        int note=0;       //initialization
        boolean ok;
        do{
            ok=true;
            try{
                note = Note();
            }       
            catch(NoNote ex){
                ok = false;
            }
            catch(NumberFormatException im){
                ok=false;
                System.out.println ("Integer please");
               
            }
        }while(!ok);
        System.out.println("Note: "+note);
    }

    static int Note() throws NoNote{
        int note;
        System.out.print("next note:");
        note = Integer.parseInt(sc.nextLine());
        
        if((note>6)||(note <2)){
            throw new NoNote("outside [2,6]");
        }
        return note;
    }
}

Example 

class Bull extends Exception{
public String s;
Bull(String par){ s = par; }
}
enum Age{YOUNG,ADULT}
enum Sex{MALE,FEMALE}
enum Run{FAST,SLOW}
class Animal {
private Age age;
private Sex sex;
Animal(Age age, Sex sex){
this.age = age;
this.sex = sex;
}
public Age age(){ return age; }
public Sex sex(){return sex;}
public String toString(){
return " animal: " + age +", "+ sex;
}
}
class Herbivore extends Animal{
public Run run;
Herbivore(Age age, Sex sex, Run run){
super(age,sex);
this.run = run;
}
public String toString(){
return super.toString() + ",herbivore:"+run;
}
}
class Carnivore extends Animal{
private boolean starving;
Carnivore(Age age, Sex sex){
super(age,sex);
starving = true;
}
public Herbivore[] tear(Herbivore[] herd) throws Bull,
ArrayIndexOutOfBoundsException{
if (starving){
if(herd[herd.length-1].age() == Age.ADULT &&
herd[herd.length-1].sex() == Sex.MALE)
throw new Bull("BULL FOUND!!");
Herbivore[] buffer = new Herbivore[herd.length-1];
System.arraycopy(herd,0,buffer,0,herd.length-1);
starving = false;
return buffer;
}
return herd;
}
public void sleep() {starving = true;}
public String toString(){
return super.toString() + " wolf , starving:" +starving;
}
}
public class MyException {
public static void prt(Animal[] animal, Animal wolf ){
System.out.println("\n\n\n animals: \n");
for(int i = 0; i < animal.length; i++)
System.out.println(""+animal[i]);
System.out.println("\n"+wolf );
}
public static void main(String[] arg){
Herbivore[] cows=new Herbivore[(int)(Math.random()*10)];
for(int i = 0; i < cows.length; i++){
cows[i] = new Herbivore(Math.random()>0.5?Age.YOUNG:Age.ADULT,
Math.random()>0.5?Sex.MALE:Sex.FEMALE,
Math.random()>0.5?Run.FAST:Run.SLOW);
}
Carnivore wolf = new Carnivore(Age.ADULT,Sex.MALE);
prt(cows,wolf );
for(;;){
try{
cows = wolf .tear(cows);
}
catch (Bull e) {
System.out.println(e.s);
System.exit(1);
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println("NO MORE COWS!");
System.exit(1);
}
wolf .sleep();
prt(cows,wolf );
}
}
}
 animals:

 animal: ADULT, FEMALE,herbivore:FAST
 animal: YOUNG, FEMALE,herbivore:FAST
 animal: ADULT, MALE,herbivore:SLOW
 animal: ADULT, MALE,herbivore:FAST
 animal: ADULT, FEMALE,herbivore:FAST
 animal: ADULT, FEMALE,herbivore:SLOW

 animal: ADULT, MALE wolf , starving:true

 animals:

 animal: ADULT, FEMALE,herbivore:FAST
 animal: YOUNG, FEMALE,herbivore:FAST
 animal: ADULT, MALE,herbivore:SLOW
 animal: ADULT, MALE,herbivore:FAST
 animal: ADULT, FEMALE,herbivore:FAST

 animal: ADULT, MALE wolf , starving:true

 animals:

 animal: ADULT, FEMALE,herbivore:FAST
 animal: YOUNG, FEMALE,herbivore:FAST
 animal: ADULT, MALE,herbivore:SLOW
 animal: ADULT, MALE,herbivore:FAST

 animal: ADULT, MALE wolf , starving:true
BULL FOUND!!

_____________________________

  animals:

 animal: YOUNG, MALE,herbivore:SLOW
 animal: YOUNG, FEMALE,herbivore:SLOW
 animal: YOUNG, FEMALE,herbivore:SLOW
 animal: YOUNG, FEMALE,herbivore:SLOW

 animal: ADULT, MALE wolf , starving:true

 animals: 

 animal: YOUNG, MALE,herbivore:SLOW
 animal: YOUNG, FEMALE,herbivore:SLOW
 animal: YOUNG, FEMALE,herbivore:SLOW

 animal: ADULT, MALE wolf , starving:true

 animals:
 animal: YOUNG, MALE,herbivore:SLOW
 animal: YOUNG, FEMALE,herbivore:SLOW

 animal: ADULT, MALE wolf , starving:true

 animals:

 animal: YOUNG, MALE,herbivore:SLOW

 animal: ADULT, MALE wolf , starving:true

 animals:

 animal: ADULT, MALE wolf , starving:true
NO MORE COWS!