EXCEPTION HANDLING IN JAVA
What is an Exception?
An exception is an unexpected event that occurs during the execution
of a program, disrupting its normal flow.
It can be thought of as a "problem" that needs to be handled, much
like how you would deal with unexpected situations in real life.
In programming, exceptions can be things like:
Invalid user input
File not found
Network issues
Why Handle Exceptions?
Handling exceptions helps you:
1. Maintain program stability.
2. Provide meaningful error messages to users.
3. Prevent the program from crashing.
Types of Exceptions in Java
1. Checked Exceptions: These are checked at compile time. For
example, trying to read a file that doesn’t exist. We handle these
using try-catch.
o Example: IOException, SQLException
2. Unchecked Exceptions: These are not checked at compile time
and are usually due to programming errors, such as dividing by
zero.
o Example:
NullPointerException, ArithmeticException
Basic Syntax of Exception Handling
Java uses try, catch, finally, and throw to handle exceptions.
1. try: Block of code where exceptions might occur.
2. catch: Block of code that handles the exception.
3. finally: Block of code that executes regardless of whether an
exception occurred or not.
4. throw: Used to explicitly throw an exception.
Example
Let’s see a simple example of handling an exception in Java:
import [Link];
public class Sample {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
try {
[Link]("Enter a number: ");
int number = [Link]();
int result = 100 / number; // This might throw
ArithmeticException
[Link]("Result: " + result);
}
catch (ArithmeticException e) {
[Link]("Error: You cannot divide by zero!");
}
catch (Exception e) {
[Link]("An error occurred: " + [Link]());
}
finally {
[Link]("Execution completed.");
[Link]();
}
}
}
1. try Block: Contains the code that may throw an exception (e.g.,
dividing by zero).
2. catch Blocks:
The first catches ArithmeticException specifically.
3. The second catches any other exceptions (using the generic
Exception class).
When catching exceptions, using [Link]() provides a
descriptive message about the error. This message can guide you
in diagnosing problems effectively.
It may prints
An error occurred: [Link] if the
input is not interger
4. finally Block: Executes regardless of whether an exception
occurred. Useful for cleanup, like closing resources.
Benefits of Exception Handling
Graceful Degradation: Instead of crashing, your application
can continue running or exit cleanly.
Debugging: Helps in identifying the source of errors with stack
traces.
User Experience: Provides meaningful feedback to users,
making your application more robust.
Conclusion
Exception handling is a crucial part of Java programming that helps
manage errors and maintain the flow of execution. By understanding
and implementing it properly, you can create more reliable and user-
friendly applications.