Exception
Exception
-During the execution of java program JVM faces abnormal situation based on the code declaration.
-If JVM faces abnormal situation then trigger an event is known as exception.
-If exception event got generated in java program then it results in termination of java program.
Exception Handling:-
-Handling the event generated by JVM durig program execution is known as exception handling.
Ex:
try{
//Risky code
}catch{
//Event handled
Try block:
Catch block:-
-catch block will get executed only once if event generated in try(abnormal situation).
-we can use finally block after try block but it not recomanded.
package exception;
try {
System.out.println(ar[3]); //Risky code
}
catch (ArithmeticException a) {
System.out.println("Arithmatic Exception Handeled");
} catch (ArrayIndexOutOfBoundsException a) {
System.out.println("arry index handled");
a.printStackTrace();
} catch (NullPointerException a) {
System.out.println("Null pointer exception handled");
} finally {
System.out.println("finally block");
}
}
package exception;
public class Test1 {
public static void main(String[] args) {
int a=10;
int b=0;
System.out.println("11111-Before risky code");
try {
int c=a/b; //Risky code
System.out.println(c);
System.out.println("222222-After risky code in try block");
}catch (ArrayIndexOutOfBoundsException c) {
System.out.println("arry index handled");
}
catch(NullPointerException c) {
System.out.println("Null pointer exception handled");
}catch (Exception d){
System.out.println("Generic Exceoption");
}
finally {
System.out.println("finally block");
}
package exception;
try {
System.out.println(s.length()); //// Risky code
System.out.println("After risky code in try block");
}
catch (ArithmeticException e) {
System.out.println("Arithmatic Exception Handeled");
e.printStackTrace();
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("arry index handled");
} catch (NullPointerException e) {
System.out.println("Null pointer exception handled");
e.printStackTrace();
}