Exception
An exception is an event which occurs during the execution of a program that disrupts the normal flow of the program’s instructions
Exception Handling
Exception handling ensures that the flow of the program doesn’t break when an exception occurs.Here’s a list of different approaches to handle exceptions in Java.
- try…catch block
- finally block
- throw and throws keyword
1)try block
The try statement allows you to define a block of code to be tested for errors while it is being executed
2)catch block
The catch statement allows you to define a block of code to be executed, if an error occurs in the try block
3)finally
The finally statement allows you execute code after try..catch.The finally block is used to execute the necessary code of the program. It is executed whether an exception is handled or not.
4)throw
The throw statement used to throw an exception
The throw statement is used together with an exception type. There are many exception types available in Java - ArithmeticException, FileNotFoundException,etc..
5)throws
The throws keyword is used to declare exceptions. It specifies that there may occur an exception in the method. It doesn’t throw an exception. It is always used with method signature.