Exceptions Explained

JVM

  1. Monitor all the statements.
  2. If an error/exception, then identifies corresponding Exception class.
  3. Create the object for Exception class.
  4. Throws the object.
  5. Catch the object & terminate the Program
  6. JVM displays info in that Object.

Exceptions Hierarchy   

     Exceptions classes are in package java.lang.*

Exceptions

There are two type of problems.

  • Exceptions which can be handled
  • Error which can’t be handled
  • All exceptions in Java are classes.
  • All exception are subclass of java.lang.Exception
  • In all exception classes – there will be only constructors. We don’t have any methods. All Exception subclasses are using superclass Throwable methods. Like getMessage(); printStackTrace();
  • We handle the Exception with the following 5 keywords.
  • try
  • catch
  • finally
  • throw
  • throws

  try: block is used to place the statements need to be monitored in case of abnormal behavior.

  catch: block is used to catch the exceptions raised by try block.

  • Catch should follow by try.
  • Other statements are not allowed between try and catch.
  • For one try – we can write more than one catch block.
  • In case of more than one catch block – order of exceptions must be subclass to superclass.

  finally:  block is used for the statements which need to be executed irrespective of exceptions occur in try block.

  • Only one finally is allowed for each try block.
  • When you have statements like System.exit(0) in try block then finally will not be executed.
  • When the running thread interrupted while executing try or catch statements by kiiling the thread then finally won’t be executed.
  • When try block goes in to infinite loop then finally won’t be executed.
  • Below are the allowed scenarios,

try{            try{            try{                try{               try{
}                 }               }                     }                   }                         
catch(){      catch(){    catch(){         catch(){       finally{     
}                }                }                   }                 }         
                catch(){     finally{           catch(){      
                }               }                    }           
                                                    finally{
                                                    }    

 

throws:  key word is used to specify the method level exceptions.  Statements inside a method may throw some exceptions. If you want to handle them – you can do that by surrounding those statements with try catch block. If you don’t want to handle the exceptions inside the method then throw them to calling method using throws at method level.

public void mtd2() throws ArrayIndexOutOfBoundsException, ArithmeticException {

//valid java statements

}

In the above method mtd2() – we are not specifying the exceptions but the we are communicating the caller method of mtd2() to handle those exception that I’m throwing.

throw: is used to throw the exceptions in ur own.  JVM handles built in exception. JVM can’t handle application level exceptions or user defined exceptions.

User Defined Exceptions:

  • Write your own exception class by extending java.land.Exception or java.lang.RuntimeException
  • Write one or more constructors based on your requirement.
  • Override toString() method.
  • If required override equals and hascode method.

Exceptions Types

Exceptions Types

Checked Exceptions examples:

UnChecked Exceptions Examples:

  • NullPointerException
  • ArrayIndexOutOfBound
  • IllegalArgumentException
  • IllegalStateException

 

Program lead to java.lang.StackOverflowError (not exception), program need to be fixed in order get rid of the error.

public static void main(String[] args) {
		method1();
	}
	static void method1(){
		method2();
	}
	static void method2(){
		method1();
	}
 

Program doesn't exit until user enter non-zero  'b' value

package com.bellinfo.batch3.corejava.day9;

import java.util.Scanner;

public class ExceptionScenario1 {
	public static void main(String[] args) {
		boolean isZero=true;
		try{	
				Scanner scan = new Scanner(System.in);
				System.out.println("enter a value:");
				int a = scan.nextInt();
				System.out.println("enter b value:");
				int b = scan.nextInt();
				int c =a/b;
				System.out.println("Result"+c);
				isZero=false;
			}catch(Exception e){
				System.out.println("Enter non zero values");
			}
	 System.out.println("Program ended normally");
	}
}

try catch finally scenarios,

public class TryCatchFinallyScenarios {

	public static void main(String[] args) {

		method1();
	}

	static void method1() {
		int a = 10;
		int b = 0;
		method2(a, b);
	}

	static void method2(int a, int b) {
		method3(a, b);
	}

	static void method3(int a, int b) {
		int c = 0;
		int array[] = new int[1];

		try {
			array[3] = 121;
			c = a / b;
		} catch (ArithmeticException e) {
			System.out.println("inside arthimetic exception");
			e.getStackTrace();
		} catch (IndexOutOfBoundsException iob) {
			System.out.println("index out of bound execption");
		} catch (Exception e) {
			System.out.println("exception class");
		} finally {
			System.out.println("finally always executes");
		}
		System.out.println("result" + c);
	}
}

scenarios where finally block doesn't execute.

		try{
			System.exit(0);
			for(;;);	
		}catch(Exception e){
			
		}
		finally{
			System.out.println("finally doesn't executes in the above two scenarios");
		}

throws scenario

public class MethodLevelExceptionsScenarios {
	public static void main(String[] args) {
		
		method1();
	}
	static void method1(){
		int a =10;
		int b =0;
		try{
		method2(a, b);
		}catch(ArithmeticException e){
			System.out.println("inside arthimetic exception");
			e.getStackTrace();
		}catch(IndexOutOfBoundsException iob){
			System.out.println("index out of bound execption");
		}catch(Exception e){
			System.out.println("exception class");
		}
		finally{
			System.out.println("finally always executes");
		}
	}
	static void method2(int a, int b) throws ArithmeticException,IndexOutOfBoundsException{
		method3(a,b);
	}
	static void method3(int a, int b) throws ArithmeticException{
		int c=0;
		int array[] = new int[1];
		array[3]=121;	
		c = a/b;
		System.out.println("result"+c);
	}
}

User Defined exceptions:

 
public class CardInvalidException extends RuntimeException {
	String number;
	
	CardInvalidException(){
		
	}
	CardInvalidException(String cardNumber){
		number = cardNumber;
	}
	
	public String toString(){
		if(number !=null){
			return "invalid card number entered"+ number +" card number must be of size 16";
		}
		return "invalid card number. Enter valid Card Number of size 16";
	}
}
import java.util.Scanner;

public class UserDefinedExceptionScenario {

	public static void main(String[] args) {
		try{
		System.out.println("Enter your card number");
		Scanner scan = new Scanner(System.in);
		String number = scan.next();
		method1(number);
		}catch(CardInvalidException cie){
			System.out.println(cie);
		}

	}
	
	static void method1(String number) throws CardInvalidException{
		if(number.length() == 16){
			System.out.println("You card has been accepted. "
					+ "And your product will be delivered soon");
		}else{
			throw new CardInvalidException(number);
		}
		
	}

}

 

Assignment

  • Write a program which throws CVV invalid exception(if it is not 3 digit number), Card invalid exception(if it is not of size 16) and expiry date(if date is not greater than today, and not in mm/yy format) and display exception message accordingly.