2 Exception Handling

Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 3

Exception: An unwanted unexpected event that distrubs normal flow of program is

called as Exception.

Exception Handling: if in our program exception occurs then we have to provide


alternate way to continue
the execution of program normally.This way of defining alternate way is nothing
but exception handling.

Example 1: When there is no exception.

package basicsOfException;

public class Demo {

public static void main(String[] args) {


System.out.println("Main method execution started");

int a = 10;
int b = 2;
int c = a / b;
System.out.println(c);

System.out.println("Main method execution Ended");


}
}

Example 2: When there is exception in our program.

package basicsOfException;

public class Demo {

public static void main(String[] args) {


System.out.println("Main method execution started");

int a = 10;
int b = 0;
int c = a / b;
System.out.println(c);

System.out.println("Main method execution Ended");


}
}

Example 3: When we handle that exception

package basicsOfException;

public class Demo {


public static void main(String[] args) {
System.out.println("Main method execution started");

int a = 10;
int b = 0;
try {
int c = a / b;
System.out.println(c);
}catch(ArithmeticException e) {

}
System.out.println("Main method execution Ended");
}
}

Types Of Exception :

1)Checked Exception
2)Unchecked Exception

1)Checked Exception: The exception which are checked by compiler is called as


Checked Exception.

Example 1 :

package typesOfException;

import java.io.FileNotFoundException;
import java.io.FileReader;

public class CheckedException {

public static void main(String[] args) {

System.out.println("Main method execution started");

try {
FileReader fr = new FileReader("C:\\Users\\HP\\OneDrive\\
Desktop\\java\\Demo.java");
} catch (FileNotFoundException e) {
System.out.println("Catch Block");
}

System.out.println("Main method execution Ended");


}
}

Example :
package typesOfException;

import java.io.FileNotFoundException;
import java.io.FileReader;

public class CheckedException {

public static void main(String[] args) {

System.out.println("Main method execution started");

try {
FileReader fr = new FileReader("C:\\Users\\HP\\OneDrive\\
Desktop\\java\\Demo11.java");
} catch (FileNotFoundException e) {
System.out.println("Catch Block");
}

System.out.println("Main method execution Ended");


}
}

2)Unchecked Exception : The Exception which are not checked by compiler is called
as Unchecked Exception.

Example :

package typesOfException;

public class UnCheckedException {

public static void main(String[] args) {


System.out.println("Main method execution started");

int a = 10;
int b = 0;
int c = a / b;

System.out.println("Main method execution Ended");


}
}

You might also like