Java Exception Handling
An exception is an object that interrupts the workflow of the program in Java.
The exception handling is a mechanism to handle the runtime errors so that the application regular workflow can be managed.
An exception handling is a mechanism to handle runtime errors such as ClassNotFoundException, SQLException, IOException, and etc.
There are 5 keywords used to handle the exception in Java:
- try
- catch
- finally
- throw
- throws
The Advantage of exception handling is help to maintain the normal workflow of the program.
Types of Exceptions in Java:
There are three types of exception handling. They are
- Check Exception
- Unchecked Exception
- Error
Check Exception
An checked exception is an exception that occurs at compilation-time. It is also called as Compile time exceptions.
Unchecked Exception
An unchecked exception is an exception that occurs at the time of execution. It is also called as Runtime Exceptions.
Error
Error is irrecoverable. Example: OutOfMemoryError, AssertionError and etc.
Java Exception Keywords
| S.No | Keyword | Description |
|---|---|---|
| 1 | Try | Try is used to protect a block of code within which exception might occur. |
| 2 | Catch | A catch statement involves declaring the sort of exception you’re making an attempt to catch. |
| 3 | Finally | A finally block of code always executes whether an exception is handled or not. |
| 4 | throw | The "throw" keyword is used to invoke an exception explicitly. |
| 5 | throws | When a method is not able to handle a checked exception, then the method should use the throws keyword. The throws keyword appears with the method's signature. |
Example
public class ExceptionHandling{
public static void main(String args[]){
try{
int a=1/0;
}
catch(ArithmeticException ae){
System.out.println(ae);
}
finally{
System.out.println("Always execute");
}
}
}
Example
public class MultipleCatch{
public static void main(String args[]){
try{
int a=1/0;
}
catch(NullPointerException e){
System.out.println(e);
}
catch(ArithmeticException e){
System.out.println(e);
}
catch(Exception e){
System.out.println(e);
}
finally{
System.out.println("Always execute");
}
}
}
Quickly Find What You Are Looking For
OnlineTpoint is a website that is meant to offer basic knowledge, practice and learning materials. Though all the examples have been tested and verified, we cannot ensure the correctness or completeness of all the information on our website. All contents published on this website are subject to copyright and are owned by OnlineTpoint. By using this website, you agree that you have read and understood our Terms of Use, Cookie Policy and Privacy Policy.
point.com