Exception Handling in java
Exception Handling is used to Handling the Error. There is a two types of Exception:Checked Exception and Unchecked Exception.
Types of of Exception Handling
- Checked Exception
- Unchecked Exception
1. Unchecked Exception
Unchecked Exception is to handle the Runtime Error.
Example
public class Main { public static void main(String [] args) { int a = 5; System.out.println(a/0); System.out.print("Hai"); } }
Output
Exception in thread "main" java.lang.ArithmeticException: / by zero
at Main.main(Main.java:6)
Using Exception Handling
Example
public class Main { public static void main(String [] args) { int a = 5; try { System.out.println(a/0); } catch(Exception e){ } System.out.print("Hai"); } }
Output
Hai
2.Checked Exception
Checked Exception is compile time Error.
Example
import java.io.*; public class Main { public static void main(String [] args) { BufferedReader read = new BufferedReader(new InputStreamReader(System.in)); String s=read.readLine(); } }
Output
error: unreported exception IOException; must be caught or declared to be thrown
String s=read.readLine();
Using Exception Handling
Example
import java.io.*; public class Main { public static void main(String [] args) throws IOException { BufferedReader read = new BufferedReader(new InputStreamReader(System.in)); String s=read.readLine(); } }
Output
Input:mycrazycoding
Same Exceptions in Java
Checked Exceptions | Unchecked Exceptions |
---|---|
ClassNotFound Exception | Arithmetic Exception |
NoSuchField Exception | ArrayIndexOutOfBounds Exception |
NoSuchMethod Exception | Null Pointer Exception |
Interrupted Exception | ClassCast Exception |
IO Exception | BufferOverflow Exception |
IllegalAccess Exception | BufferUnderflow Exception |
More About
1.Try catch block 2.Multiple Catch Block 3.Try catch finally 4.Throw and throws