← Previous Post
File Handling in Java
Next Post →
Introduction to Java Programming
Exceptions are unexpected events that disrupt the normal flow of program execution. While some can be handled programmatically, critical errors such as system-level failures can impact application stability. In Java, an exception is an object derived from the Throwable superclass.Most of the time exception can be created with the following conditions:
When an exception occurs during program execution, the runtime system generates a stack trace ,a structured report that provides valuable diagnostic information to help developers locate and fix the problem.A typical stack trace includes the following key elements:
At the root of Java's exception hierarchy is the Throwable class, which has two main branches: Error and Exception.For example, Errors like InternalError, OutOfMemoryError, and AssertionError are examples of system-level failures. Exceptions, on the other hand, include things such as IOException and RuntimeException.To get detail information about exception,See: Throwable API Documentation
Built-in exceptions are provided by Java libraries and can be classified as checked or unchecked exceptions.
User-defined exceptions are custom exceptions which are created by programmers to handle application-specific scenarios and are helpful for debugging and edge-case handling.For instance,
public class CustomException extends Exception {
public CustomException(String message) {
super(message);
}
}
public class TestCustomException {
static void validate(int age) throws CustomException {
if (age < 20) {
throw new CustomException("Age is not valid for our purpose");
} else {
System.out.println("It is good");
}
}
public static void main(String[] args) {
try {
Scanner sc = new Scanner(System.in);
System.out.println("Enter age:");
int age = sc.nextInt();
validate(age);
} catch (CustomException ex) {
System.err.println("Exception occurred: " + ex);
}
}
}
In real-world applications, errors are inevitable due to invalid inputs, hardware failures, or unpredictable runtime conditions. Without proper handling, these can lead to application crashes and data loss.
Java provides a robust mechanism for handling such errors using try-catch blocks, the throw and throws keywords, and custom exception classes. This approach ensures smoother execution and better user experience by gracefully managing runtime anomalies. Use try-catch blocks to catch and resolve exceptions.
To explicitly create an exception while a program is running, use the throw keyword. The software searches for a specific piece of code known as an exception handler to handle the error when an exception is thrown, disrupting the program's normal flow.
Syntax: throw new ExceptionType("Error message");For example,
public class ThrowKeyword {
public static void checkAge(int age) {
if (age <16) {
throw new IllegalArgumentException("Age must be greater than 16.");
}
System.out.println("Age is: " + age);
}
public static void main(String[] args) {
try {
checkAge(10); // will throw an exception
} catch (IllegalArgumentException e) {
System.out.println("Exception: " + e.getMessage());
}
checkAge(6); // This call will not throw an exception
}
}
The throws keyword is used in method declarations to indicate that a method may throw certain exceptions. The caller must handle these using a try-catch block.
Syntax: type method_name(parameters) throws exception_list
Note: The exception_list used in a program can either be predefined by Java (built-in exceptions) or defined by the programmer (custom exceptions) to handle specific situations.For example,
static void validate(int age) throws CustomException {
if(age < 18) {
throw new CustomException("The age is invalid");
}
}
A key component of Java's exception-handling mechanism is the finally block. It defines a section of code that always executes, regardless of whether an exception is thrown or caught. This makes it particularly useful for performing essential cleanup operations, such as closing files or releasing resources.Main features include
public class SimpleFinallyBlock {
public static void main(String[] args) {
try {
Scanner sc = new Scanner(System.in);
int first = sc.nextInt();
int second = sc.nextInt();
int result = divide(first, second);
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.err.println("Exception: " + e);
} finally {
System.out.println("Good Bye!!");
}
}
public static int divide(int a, int b) {
return a / b;
}
}
How to Configure Ad hoc Wireless Network.
Object Oriented Programming in C++ for Beginners.
Database Fundamentals for Beginners.
I’m committed to providing tailored solutions and always ready to assist if any issue arises.