EXCEPTION HANDLING

An exception (or exceptional event) is a problem that arises during the execution of a program. Exception normally disrupts the normal flow of the application that is why we use exception handling.

TYPES OF EXCEPTION

CHECKED EXCEPTION :

A checked exception is an exception that occurs at the compile time.

Examples:

  • IOException
  • EOFException
  • SQLException

UNCHECKED EXCEPTION :

An unchecked exception is an exception that occurs at the time of execution.

Examples :

  • NullPointerException
  • NumberFormatException
  • ArithmeticException

ERROR :

Error is irrecoverable.

Examples :

  • VirtualMachineError,
  • AssertionError

TRY-CATCH BLOCK

Java try block is used to enclose the code that might throw an exception. It must be used within the method.

Java catch block is used to handle the Exception. It must be used after the try block only.

FINALLY

  • Java finally block is a block that is used to execute important code such as closing connection, stream etc.
  • Java finally block is always executed whether exception is handled or not.

THROW

The Java throw keyword is used to explicitly throw an exception.We can throw either checked or uncheked exception in java by throw keyword.

THROWS

The Java throws keyword is used to declare an exception. It gives an information to the programmer that there may occur an exception.

CUSTOM EXCEPION

Custom Exception are the exceptions which are created by programmer.

All terms studied so far , shown in the given example :

class ThrowExceptionOnAge extends Exception{      //Custom exception
	ThrowExceptionOnAge(){
		System.out.println("No Entry");
	}
	ThrowExceptionOnAge(String s){
		System.out.println(s);
	}
}
public class ExceptionDemo{
	public static void main(String args[]) throws ThrowExceptionOnAge{     //throws keyword
		int age;
		age=2;
		try{                 //try block
		   if(age<18){
			throw new ThrowExceptionOnAge("Get out");    //throw keyword
		    }
	            else{
			System.out.println("Welcome");
		    }
		}
		catch(ThrowExceptionOnAge e){       //catch block
			System.out.println(e);
		}
                finally{                      //finally block
                       System.out.println("Bye");
	 }
     }
}

Output :

Get Out
ThrowExceptionOnAge
Bye

 

Leave a comment