what is exception in java with example
In Java, an exception is an event that disrupts the normal flow of a program’s instructions during execution. Exceptions are used to handle errors and other exceptional events that can occur in a Java program. When an exceptional event occurs, an object representing that exception is created and thrown in the method that caused the error.
Here’s a basic overview of exceptions in Java:
1. Throwing an Exception: You can throw an exception explicitly using the
throw keyword. For example, you might throw an exception if a certain condition is not met:
2. Catching an Exception: Exceptions are caught using
finally blocks. Code that might throw an exception is enclosed within a
try block, and if an exception occurs, it’s caught and handled in a corresponding
catch block, you can handle the exception, log the error, or take any necessary corrective action.
Types of Exceptions
Types of Exceptions: There are two main types of exceptions in Java: checked exceptions and unchecked exceptions.
- Checked Exceptions (Compile time Exceptions)
- Unchecked Exceptions (Runtime Exceptions)
1. Checked Exceptions: These are exceptions that are checked at compile-time. If a method is capable of causing a checked exception, it must declare that it throws the exception using the
2. Unchecked Exceptions (Runtime Exceptions): These are exceptions that are not checked at compile-time. They extend the
RuntimeException class. Examples include
ArrayIndexOutOfBoundsException, etc. Methods are not required to declare that they may throw unchecked exceptions.
Unchecked exceptions are often caused by bugs in the code (such as trying to access an array element that doesn’t exist), while checked exceptions are usually related to external factors, like file I/O operations or network connections.
Custom Exceptions: You can also create your own custom exceptions by extending the
Exception class or any of its subclasses. Custom exceptions allow you to define specific exception types for your application.
And then you can throw and catch your custom exception like any other exception.
Exceptions in Java provide a way to handle errors and exceptional situations gracefully, allowing the program to recover or terminate without crashing. They are an essential part of Java’s error handling mechanism, ensuring robust and reliable applications.