Exceptions – Checked and Runtime Exceptions with Examples: (Custom Exceptions here)
What is an Exception?
Exceptions are events that occurs during program execution.
What are the types of Exception?
There are two types of exceptions,
- Checked Exception
- Unchecked / Runtime Exceptions
What is the difference between Error and Exceptions?
Error:
Errors are subclass of Throwable. Errors are something which cannot be recovered and it is best practice not to try-catch the errors.
Example: OutofMemory Error
Exceptions:
Exceptions are subclass of Throwable. Exceptions are something which can be recovered.
Example: IO Exception
Difference Between Checked Exceptions and Runtime Exceptions:
Checked Exceptions | Unchecked Exceptions |
---|---|
Checked Exceptions can be caught and handled at Compile Time | Unchecked Exceptions occurs at Runtime |
Checked Exceptions are direct subclass of exceptions | Unchecked Exceptions are subclass of Runtime Exceptions |
Examples: IO Exception, Arithmetic exceptions etc. | Examples: ArrayIndexOutofBound Exception, NullPointer exception etc |
Example for Checked and Runtime Exceptions,
ExceptionHandling.java
package ExceptionHandling; public class ExceptionHandling { public void checkedException(){ try{ int i=2/0; System.out.println(i); } catch(Exception e){ e.printStackTrace(); } } public void uncheckedException(){ try{ int array_Elements[] = {1,2,3,4,5}; System.out.println(array_Elements[6]); } catch (Exception e){ e.printStackTrace(); } } public static void main(String args[]){ ExceptionHandling exceptionHandling = new ExceptionHandling(); exceptionHandling.checkedException(); exceptionHandling.uncheckedException(); } }
CustomExceptions – Here
[…] Custom Exceptions: (Exceptions here) In Java, developer can customize the exceptions. The developer has to write a class that extends […]