You are on page 1of 2

CSE 1007

USER DEFINED EXCEPTION


class InvalidAgeException extends Exception{
InvalidAgeException(String s){
super(s);
}
}
class TestCustomException1{
static void validate(int age)throws InvalidAgeException{
if(age<18)
throw new InvalidAgeException("not valid");
else
System.out.println("welcome to vote");
}
public static void main(String args[]){
try{
validate(13);
}catch(Exception m){System.out.println("Exception occured: "+m);}
System.out.println("rest of the code...");
}
}

[All checked and unchecked exceptions handled as well as created for


your own scenario]

import java.util.*;
import java.lang.*;
class Example{
public static void main(String args[]){
try{
int arr[]=new int[7];
arr[10]=10/5;
System.out.println("Last Statement of try block");
}
catch(ArithmeticException e){
System.out.println("You should not divide a number by zero");
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println("Accessing array elements outside of the limit");
}
System.out.println("Out of the try-catch block");
try{
int b=20/0;
System.out.println("Last Statement of try block");}
catch(ArithmeticException e){
System.out.println("You should not divide a number by zero");
}
System.out.println("Out of the try-catch block");
try{
String str=null;
System.out.println (str.length());
}
catch(NullPointerException e){
System.out.println("NullPointerException..");
}
System.out.println("Out of the try-catch block");
}
}

You might also like