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 optimized for basic learning, practice and more. Examples are well checked and working examples available on this website but we can't give assurity for 100% correctness of all the content. This site under copyright content belongs to Onlinetpoint. You agree to have read and accepted our terms of use, cookie and privacy policy.