0% found this document useful (0 votes)
2 views

Exception Handling

Exception handling in Java allows for the management of runtime errors to maintain the normal flow of applications, making programs more robust. Key concepts include checked and unchecked exceptions, along with keywords like try, catch, finally, throw, and throws for managing exceptions. The document also provides examples of handling various exceptions such as ArithmeticException, ArrayIndexOutOfBoundsException, and FileNotFoundException.

Uploaded by

sandhya.sharma
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Exception Handling

Exception handling in Java allows for the management of runtime errors to maintain the normal flow of applications, making programs more robust. Key concepts include checked and unchecked exceptions, along with keywords like try, catch, finally, throw, and throws for managing exceptions. The document also provides examples of handling various exceptions such as ArithmeticException, ArrayIndexOutOfBoundsException, and FileNotFoundException.

Uploaded by

sandhya.sharma
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 6

Exception handling

Exception handling in Java is a mechanism that allows you to handle runtime errors, so the
normal flow of the application can be maintained. It helps in making your program more robust
and prevents it from crashing unexpectedly.

🔹 Key Concepts of Exception Handling in Java

1. What is an Exception?

An exception is an event that occurs during the execution of a program and disrupts the normal
flow of instructions. It is an object that represents an error.

2. Types of Exceptions

 Checked Exceptions – These are checked at compile-time (e.g., IOException,


SQLException).
 Unchecked Exceptions – These occur at runtime and are not checked at compile-time
(e.g., NullPointerException, ArithmeticException).

🔹 Exception Handling Keywords


try

Wrap the code that might throw an exception.

catch

Handle the exception.

finally

Code that will execute no matter what (used for cleanup, like closing a file or DB connection).

throw

Used to explicitly throw an exception.

throws

Declares exceptions in the method signature.


🔹 Basic Syntax Example
public class Example {
public static void main(String[] args) {
try {
int result = 10 / 0; // This will throw
ArithmeticException
}
catch (ArithmeticException e)
{
System.out.println("Can't divide by zero!");
}
finally
{
System.out.println("This block always runs.");
}
}
}

🔹 Using throws with Methods


public void readFile(String filename) throws IOException {
FileReader file = new FileReader(filename);
// method code
}

🔹 Custom Exceptions

You can create your own exceptions by extending Exception class.

class MyException extends Exception {


public MyException(String message) {
super(message);
}
}

Let's break down the method:

public void readFile(String filename) throws IOException {


FileReader file = new FileReader(filename);
// method code
}
🔍 Line-by-Line Explanation

🔹 public void readFile(String filename)

This is a method declaration:

 public: The method is accessible from outside the class.


 void: The method does not return anything.
 readFile: The method name.
 String filename: It takes one parameter — the name of the file to be read (as a string).

🔹 throws IOException

This part means that the method might throw an IOException, and it’s not handling it directly
inside the method. Instead, it passes the responsibility of handling the exception to whoever calls
the method.

 IOException is a checked exception — the compiler requires it to be either handled


with a try-catch block or declared with throws.

🔹 FileReader file = new FileReader(filename);

This line creates a FileReader object, which tries to open and read the specified file.

 If the file doesn’t exist, or there's an error accessing it, Java will throw an IOException.
 That’s why the method must declare throws IOException.

💡 Example of Calling This Method


public class Test {
public static void main(String[] args) {
try {
readFile("test.txt");
} catch (IOException e) {
System.out.println("An error occurred while reading the file: " +
e.getMessage());
}
}

public static void readFile(String filename) throws IOException {


FileReader file = new FileReader(filename);
// Add reading logic here
file.close(); // don't forget to close the file!
}
}

Want me to add reading the file line by line or using BufferedReader?

4o

You said:

some other example of exception handling


ChatGPT said:

Absolutely! Here are a few more practical examples of exception handling in Java — each
showing different types of exceptions and how to handle them.

✅ 1. ArithmeticException (Divide by Zero)


public class DivideExample {
public static void main(String[] args) {
try {
int a = 10;
int b = 0;
int result = a / b; // will throw ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Error: Cannot divide by zero!");
}
}
}

✅ 2. ArrayIndexOutOfBoundsException
public class ArrayExample {
public static void main(String[] args)
{
int[] numbers = {1, 2, 3};
try
{
System.out.println(numbers[5]); // invalid index
}
catch (ArrayIndexOutOfBoundsException e)
{
System.out.println("Error: Index out of bounds!");
}
}
}
✅ 3. NullPointerException

public class NullPointerExample {


public static void main(String[] args)
{
String text = null;
try {
System.out.println(text.length()); // throws
NullPointerException
}
catch (NullPointerException e)
{
System.out.println("Error: Tried to access
something on a null object!");
}
}
}

✅ 4. FileNotFoundException (with throws)


java
CopyEdit
import java.io.*;

public class FileExample {


public static void main(String[] args) {
try {
readFile("notfound.txt");
} catch (FileNotFoundException e) {
System.out.println("File not found: " + e.getMessage());
}
}

public static void readFile(String filename) throws FileNotFoundException


{
FileReader fr = new FileReader(filename); // throws
FileNotFoundException
// Logic to read the file here
}
}

✅ 5. Multiple catch Blocks


java
CopyEdit
public class MultiCatchExample {
public static void main(String[] args) {
try {
int[] arr = new int[3];
arr[5] = 10; // ArrayIndexOutOfBoundsException
int x = 5 / 0; // ArithmeticException
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array error: " + e.getMessage());
} catch (ArithmeticException e) {
System.out.println("Math error: " + e.getMessage());
}
}
}

Let me know if you want examples of:

 finally block
 throw and custom exceptions
 real-world cases (like login validation, API calls, etc.)

You might also like