User defined Exceptions in Java with Example – Exception Handling

By | December 22, 2010
You can learn about User defined Exceptions in Java with Example Program. In this tutorial you can find user defined exception concept in java Exception Handling with example.

You can learn about User defined Exceptions in Java with Example Program. In this tutorial you can find user defined exception concept in java Exception Handling with example.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
class MyException extends Exception{
MyException(){}
public String toString(){
return “User created Exception occurred “;
}
}
public class UserExceptionDemo {
public static void main(String[] args) {
try {
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
System.out.println(“Enter number”);
int a = Integer.parseInt(br.readLine());
System.out.println(“Enter number”);
int b = Integer.parseInt(br.readLine());
display(a,b);
} catch (MyException e) {
System.out.println(e);
}catch (IOException e) {
System.out.println(e);
}
}
static void display(int x,int y)throws MyException{
if(x>y){
throw new MyException();
}else {
System.out.println(“Exception not occured”);
}
}
}
Result:
i)
Enter number
2
Enter number
3
Exception not occurred
ii)
Enter number
4
Enter number
2
User created Exception occurred

Leave a Reply

Your email address will not be published. Required fields are marked *