Java provides a rich set of built-in exceptions to
handle different types of errors that occur during program execution.
Additionally, Java allows developers to create custom exceptions to
define application-specific error scenarios.
1. Built-in
Exceptions in Java
Java’s built-in exceptions are part of the java.lang package and are categorized into:
A. Checked
Exceptions (Compile-time Exceptions)
Checked exceptions are exceptions that the compiler
forces you to handle using try-catch or throws. These occur due
to external factors like file access errors or database failures.
Exception |
Description |
IOException |
General input-output failure. |
FileNotFoundException |
File not found in the specified path. |
SQLException |
Error in SQL operations. |
InterruptedException |
A thread is interrupted while waiting. |
ClassNotFoundException |
Class definition is missing. |
CloneNotSupportedException |
clone() is called on an object that does not implement Cloneable. |
Example of
Checked Exception: Handling IOException
java
CopyEdit
import java.io.*;
public class CheckedExceptionExample
{
public static void main(String[] args) {
try {
FileReader file = new FileReader("non_existent_file.txt");
// Throws FileNotFoundException
BufferedReader br = new BufferedReader(file);
} catch (IOException e) {
System.out.println("File not
found: " + e.getMessage());
}
}
}
B. Unchecked
Exceptions (Runtime Exceptions)
Unchecked exceptions are not checked at compile time
and occur due to logical errors in the program.
Exception |
Description |
ArithmeticException |
Divide by zero error. |
NullPointerException |
Accessing an object reference that is null. |
ArrayIndexOutOfBoundsException |
Accessing an array element outside the valid range. |
StringIndexOutOfBoundsException |
Accessing a character outside the valid index in a string. |
ClassCastException |
Invalid type casting. |
NumberFormatException |
Converting an invalid string to a number. |
Example of
Unchecked Exception: Handling NullPointerException
java
CopyEdit
public class UncheckedExceptionExample
{
public static void main(String[] args) {
String str = null;
try {
System.out.println(str.length()); //
Throws NullPointerException
} catch (NullPointerException e) {
System.out.println("String is
null, cannot find length.");
}
}
}
C. Errors
(System-level Exceptions)
Errors are serious failures related to the JVM or
system, and they should not be handled in most cases.
Error |
Description |
OutOfMemoryError |
JVM runs out of memory. |
StackOverflowError |
Infinite recursion leading to stack overflow. |
VirtualMachineError |
JVM-related error. |
Example of Error:
StackOverflowError
java
CopyEdit
public class ErrorExample
{
public static void recursiveMethod() {
recursiveMethod(); // Infinite
recursion causes StackOverflowError
}
public static void main(String[] args) {
recursiveMethod();
}
}
2. Creating
Custom Exceptions in Java
Java allows developers to define custom
exceptions by extending the Exception class (for checked exceptions) or the RuntimeException class (for unchecked exceptions).
A. Creating a
Custom Checked Exception
- We extend the Exception class.
- Since it is checked, it must be handled using try-catch or throws.
java
CopyEdit
class AgeException
extends Exception {
public AgeException(String message) {
super(message);
}
}
public class CustomCheckedException
{
static void checkAge(int age) throws
AgeException {
if (age < 18) {
throw new AgeException("Age
must be 18 or above.");
}
}
public static void main(String[] args) {
try {
checkAge(16);
} catch (AgeException e) {
System.out.println("Caught
Exception: " + e.getMessage());
}
}
}
B. Creating a
Custom Unchecked Exception
- We extend the RuntimeException class.
- Since it is unchecked, it does not need to be explicitly caught.
java
CopyEdit
class InvalidInputException
extends RuntimeException {
public InvalidInputException(String
message) {
super(message);
}
}
public class CustomUncheckedException
{
static void validate(int number) {
if (number < 0) {
throw new InvalidInputException("Number
cannot be negative.");
}
}
public static void main(String[] args) {
validate(-5); // Will throw
InvalidInputException
}
}
Key Differences
Between Built-in and Custom Exceptions
Feature |
Built-in Exceptions |
Custom Exceptions |
Predefined by Java |
Yes |
No |
Requires extends keyword? |
No |
Yes |
Needs explicit handling? |
Yes (for checked exceptions) |
Yes (for checked exceptions) |
Can be tailored for application-specific needs? |
No |
Yes |
Conclusion
- Java provides built-in exceptions categorized as checked,
unchecked, and errors.
- Checked exceptions need to be
handled at compile time, while unchecked exceptions occur due to
logical errors.
- Errors represent critical system failures.
- Java allows the creation of custom exceptions for specific
application needs, improving clarity and maintainability.
- Custom checked exceptions must be
explicitly handled, while custom unchecked exceptions do not
require handling.
No comments:
Post a Comment