Day 1: Introduction to Java

icon picker
Day 9: Exception Handling in Java

Welcome back to our Java programming journey! Today, we dive into a crucial aspect of Java - Exception Handling. Exceptions are a fundamental concept in Java that allow you to gracefully handle errors and unexpected situations in your code. In this blog post, we will explore what exceptions are, how to use try-catch blocks, understand different types of exceptions (checked and unchecked), and even learn how to create custom exceptions.

What are Exceptions?

In Java, an exception is an event that disrupts the normal flow of a program. When an exception occurs, it can be caused by various reasons, such as invalid input, network issues, or file not found, among others. Exceptions are essential for maintaining the stability and robustness of your Java applications.
Exceptions can occur at runtime and can lead to your program terminating abruptly if not handled properly. To prevent this, Java provides a structured way to handle exceptions.

try-catch Blocks

The primary mechanism for handling exceptions in Java is the try-catch block. Here's how it works:
javaCopy code
try {
// Code that might cause an exception
} catch (ExceptionType e) {
// Code to handle the exception
}

The code inside the try block is the code where you anticipate an exception might occur.
If an exception occurs inside the try block, the control will immediately transfer to the catch block.
The catch block specifies the type of exception it can handle (e.g., NullPointerException, IOException, etc.), and it contains code to handle the exception.
Here's an example:
javaCopy code
try {
int result = 5 / 0; // This will cause an ArithmeticException
} catch (ArithmeticException e) {
System.out.println("An arithmetic exception occurred: " + e.getMessage());
}

Exception Types (Checked and Unchecked)

In Java, exceptions are categorized into two types:

Checked Exceptions:

These are exceptions that the compiler checks at compile-time, and you must either catch them using try-catch or declare that your method may throw them using the throws keyword. Examples include IOException, SQLException, etc.

Unchecked Exceptions (Runtime Exceptions):

Unchecked exceptions are not checked by the compiler, and they typically occur due to programming errors, such as dividing by zero or accessing a null reference. Examples include NullPointerException, ArrayIndexOutOfBoundsException, ArithmeticException, etc.

Custom Exceptions

You can also create your own custom exceptions in Java by extending the Exception class or one of its subclasses. This allows you to define specific exception types for your application. Here's a simple example:
javaCopy code
class CustomException extends Exception {
public CustomException(String message) {
super(message);
}
}

Now you can throw and catch your custom exception:
javaCopy code
try {
throw new CustomException("This is a custom exception!");
} catch (CustomException e) {
System.out.println("Caught custom exception: " + e.getMessage());
}

Example -

class ArrayIndexOutOfBounds
{

public static void main(String[] args)
{

String languages[] = {"C", "C++", "Java", "Perl", "Python"};

try
{

for (int c = 1; c <= 5; c++)
{

System.out.println(languages[c]);

}

}
catch (Exception e)
{

System.out.println(e);

}
}
}


class MyOwnException
{

public static void main(String[] a)
{

try
{

MyOwnException.myTest(null);

}
catch (MyAppException mae)
{

System.out.println("Inside catch block: " + mae.getMessage());

}
}

static void myTest(String str) throws MyAppException
Want to print your doc?
This is not the way.
Try clicking the ⋯ next to your doc name or using a keyboard shortcut (
CtrlP
) instead.