Checked Exceptions:
Checked Exceptions are those exceptions which are checked during compile time. If a program contains checked exception then it should be handled using try-catch block or by using throws keyword, otherwise there will be a compile-time error.
Example of Checked Exception:
import java.io.File;
import java.io.FileReader;
public class CheckedExcDemo {
public static void main(String args[]){
File file=new File("E://check.txt");
FileReader fr = new FileReader(file);
}
}
The above program will give a checked exception( FileNotFoundException) if the file does not found as provided in the path
Unchecked Exception:
Unchecked Exceptions are those exceptions which are not checked during compile time and exception is thrown during run time. So if we do not handle it using either try/catch block or using throws keyword there will be no compile time error and program will execute but will throw a run time error.
class Example {
public static void main(String args[])
{
int num1=10;
int num2=0;
//Divide by zero Exception will be thrown at run time
int result=num1/num2;
System.out.print(result);
}
}
The above program will throw a runtime exception(ArithmeticException
) as it will not show any error during compiling.
0 Comment(s)