Categories
Core JAVA

Exception Handling in Java

Exception Handling

It is a situation in which the program terminates abnormally.
In Java, an exception is divided into two categories:-

  1. If an exception occurs at the time of run time of compilation is known as a checked exception.
  2. If an exception occurs at the time of compile-time it is known as an unchecked exception.

Java support 5 keywords to handle the exception or Exception Handling:-

1)Try
2)Catch

exception handling

3)Throw
4)Throws
5)Finally

Try:-

Try is a keyword that is used to declare a block, which is known as to try block.
Try is not an independent block
It depends upon catch and finally.
Try should be followed by catch or finally block.
Generally, try block contains generate codes.

Catch

The catch is a which is used to declare block known as catch block java.
The execution of the catch block is optional but the execution of the try block is compulsory.
Try block always after satisfying two conditions:-
–>The code present within try block should generate the exception.
–>The corresponding exception handler should be handled in the catch.

The syntax of try with the catch:-
try
{
//exception generate codes
}
catch(Throwable Object)
{
//Exception Handle Codes
}

Throw:-

Java throw keyword is used to explicitly throw an exception.
The checked exception cannot be propagated using thrown only.
The throw is followed by an instance.
The throw is used within the method.
We cannot throw multiple exceptions.

Throws:-

Java throws keyword is used to declare an exception.
The checked exception can be propagated using thrown only.
The throw is followed by a class.
The throw is used with the method signature (Prototype).
We can declare multiple exceptions.

Finally:-

This is very similar to the catch block.
Finally, block only can be placed after the try block.

Leave a Reply

Your email address will not be published. Required fields are marked *