Exception Handling
Exception Handling
Preapered by
Tanusree Saha
What is an exception?
If an exception occurs, which has not been handled by programmer then program
execution gets terminated and a system generated error message is shown to the user.
For example look at the system generated exception below:
This message is not user friendly so a user will not be able to understand what
went wrong. In order to let them know the reason in simple language, we
handle exceptions. We handle such conditions and then prints a user friendly
warning message to user, which lets them correct the error as most of the
time exception occurs due to bad data provided by user.
Advantage of exception handling
Try
The "try" keyword is used to specify a block where we should place exception code.
The try block must be followed by either catch or finally. It means, we can't use try
block alone.
Catch
The "catch" block is used to handle the exception. It must be preceded by try block
which means we can't use catch block alone. It can be followed by finally block
later.
Finally
The "finally" block is used to execute the important code of the program. It is
executed whether an exception is handled or not.
Throw
The "throw" keyword is used to throw an exception.
Throws
The "throws" keyword is used to declare exceptions. It doesn't throw an exception. It
specifies that there may occur an exception in the method. It is always used with
method signature.
Java Exception Handling Example
:
3) A scenario where NumberFormatException occurs
The wrong formatting of any value may occur