What is Exception?
Exception is an event that occurs during an execution of a program that disrupts the normal flow the program.
To handle these exceptions, there be a concept in java that is Exception handling; it maintains the normal flow of the program.
Main advantage of exception handling is that it’s maintain the normal flow of the program and Separate error handling code form normal code.
Exception can be occurred due to wrong input data e.g. divide by zero.
Types of Exceptions —
• Checked exceptions — All exceptions except runtime exceptions are checked exceptions.
• Unchecked exceptions — All runtime exceptions are unchecked exceptions.
• Errors — Errors are not recoverable.
Try / catch block –
Error prone code is placed in try block and catch block is used to handle that error, try block should be always followed by catch or finally block.
In this block, we placed important code that should be executed whether the exception is handled or not.
Throw keyword that allows the user to throw an exception or any class that implements “throwable” exception.Throws –
A java keyword used in method declarations that specify which exceptions are not handled within the method but rather passed through the next higher level of the program.A basic Program to show how try/catch block works.
In this example, we have divided the no. by zero and it gives an error.
Program to show how finally block executes.
Here in try block we placed a error prone code and handle in catch block and in finally block we placed our rest code.
Program to show how throw keyword works.