Exception Handling in Java
- throw: Used to explicitly generate exceptions in code. For example, throwing an exception when a required parameter is null in a user authentication program.
- throws: Declares exceptions that might be thrown by a method but are not handled within the method itself. It informs the caller method about potential exceptions that need to be handled.
- try-catch: Used for exception handling in Java. The code that may throw an exception is enclosed within the try block, and exceptions are caught and handled in the catch block(s).
- finally: An optional block that follows a try-catch block. It is used for cleanup tasks and always executes, regardless of whether an exception occurred or not.
/*package whatever //do not write package name here */
import java.io.*;
class GFG {
// Function to throw ArithmeticException
public static void divide(int num, int den)
throws ArithmeticException
{
if (den == 0) {
throw new ArithmeticException(
"Division by zero error");
}
System.out.print("Result of division: "
+ num / den);
}
public static void main(String[] args)
{
int numerator = 5;
int denominator = 0;
try {
divide(numerator, denominator);
}
catch (ArithmeticException e) {
System.out.print("Error: " + e.getMessage());
}
finally {
System.out.println();
}
}
}
Output
Error: Division by zero error
Exception Handling in Programming
Exception handling is a critical aspect of programming, enabling developers to manage unexpected or erroneous situations gracefully. In this article, we’ll discuss the concept of exception handling, its importance, and best practices for implementing it effectively in various programming languages.
Table of Content
- What is Exception Handling?
- Components of Exception Handling
- Exception Handling in C
- Exception Handling in C++
- Exception Handling in Java
- Exception Handling in Python
- Exception Handling in C#
- Exception Handling in JavaScript
- Exception Handling Best Practices
Contact Us