Java Basic Tutorial
Java Advance Tutorial
Exception handling in Java is a mechanism that allows you to handle runtime errors so that normal program flow is not disrupted. It helps prevent unexpected crashes and improves application stability.
An exception is an unwanted or unexpected event that occurs during program execution. It disrupts the normal flow of instructions.
IOException
, SQLException
NullPointerException
, ArithmeticException
OutOfMemoryError
, StackOverflowError
Java provides five keywords for exception handling:
Keyword |
Description |
---|---|
try |
Defines a block of code to test for exceptions. |
catch |
Handles the exception if one occurs. |
finally |
A block that executes always, whether an exception occurs or not. |
throw |
Used to manually throw an exception. |
throws |
Declares exceptions that a method might throw. |
Try it yourself
You can handle different exceptions separately using multiple catch
blocks.
Try it yourself
The finally
block always executes whether an exception occurs or not.
Try it yourself
Try it yourself
If a method does not handle an exception, it can declare it using throws
.
Try it yourself
You can create your own exception class by extending Exception
.
Try it yourself