Tuesday, 13 October 2015

Custom exception handling example in java


public class First {

public static void main(String[] args) {
// TODO Auto-generated method stub
for(int i=0;i<10;i++){
try{
System.out.println("The value is " +i);

if(i==0){
Myexception m = new Myexception("Less than 10");
throw m;
}
}
catch(Myexception m){
m.printStackTrace();

}
finally{
System.out.println("I am in final block");
}
}
}

}


public class Myexception extends Exception {
String j;
Myexception(){
System.out.println("Default constructed");
}
Myexception(String i){
super(i);
}
}

output:-
The value is 0
Myexception: Less than 10
at First.main(First.java:11)
I am in final block
The value is 1
I am in final block
The value is 2
I am in final block
The value is 3
I am in final block
The value is 4
I am in final block
The value is 5
I am in final block
The value is 6
I am in final block
The value is 7
I am in final block
The value is 8
I am in final block
The value is 9
I am in final block

No comments:

Post a Comment