Module 5
Module 5
Java provides a robust set of built-in exception types that fall under two main
categories:
1. Checked Exceptions
• Definition: These are exceptions that are checked at compile-time. If a method can
throw a checked exception, it must declare this in its method signature using the throws
keyword, or the exception must be handled within the method.
• Examples:
o IOException
o SQLException
o FileNotFoundException
• Definition: These exceptions are not checked at compile-time, and they occur during
the execution of the program. They are the result of programming errors, such as logic
mistakes or incorrect use of APIs. Unchecked exceptions do not need to be declared or
caught explicitly.
• Examples:
o NullPointerException
o ArrayIndexOutOfBoundsException
o ArithmeticException
3. Errors
• Definition: Errors are serious problems that a reasonable application should not try to
catch or handle. These are usually external to the application and caused by problems
like system failures.
• Examples:
o OutOfMemoryError
o StackOverflowError
Common Errors:
• OutOfMemoryError: Thrown when the Java Virtual Machine (JVM) cannot allocate an
object because it is out of memory.
• StackOverflowError: Thrown when a stack overflow occurs, typically due to excessive
recursion.
Custom Exceptions
java
Copy code
super(message);
Copy code
try {
} catch (ExceptionType1 e) {
} catch (ExceptionType2 e) {
} finally {
This is an overview of exception types and handling in Java, helping to manage errors
and maintain program flow.
4o
You said:
Structure of try-catch-finally:
1. try block: Contains the code that may throw an exception. Only one try block is allowed,
and it must be followed by one or more catch blocks, or a finally block, or both.
2. catch block(s): Used to handle specific exceptions that may be thrown by the code in
the try block. You can have multiple catch blocks to handle different types of
exceptions. Each block catches a specific type of exception.
3. finally block (optional): Executes regardless of whether an exception occurred or not.
It's often used for cleanup activities like closing files, releasing resources, or closing
database connections.
Syntax:
java
Copy code
try {
} catch (ExceptionType1 e) {
} catch (ExceptionType2 e) {
} finally {
Example of try-catch-finally:
java
Copy code
import java.io.*;
try {
System.out.println(a);
} catch (FileNotFoundException e) {
} catch (IOException e) {
} finally {
if (file != null) {
try {
file.close();
} catch (IOException e) {
Explanation:
• try block: Attempts to open and read from a file. The code here is "risky" because it may
throw exceptions, such as FileNotFoundException if the file does not exist, or
IOException if an input/output error occurs.
• catch block: Catches exceptions thrown within the try block.
o If the file is not found, the first catch block catches the FileNotFoundException.
o If an I/O error occurs, the second catch block catches the IOException.
• finally block: Always runs whether or not an exception was thrown. It's used here to
close the file and ensure that the resource is released.
Key Points:
1. Multiple catch blocks:
o You can have multiple catch blocks for different types of exceptions.
o If an exception occurs, the JVM checks each catch block in order. The first one
that matches the exception type is executed, and then control moves out of the
try-catch-finally structure.
2. finally block execution:
o The finally block is always executed, even if an exception occurs or if there's a
return statement inside the try or catch blocks.
o It is primarily used for resource cleanup (like closing files or network
connections).
java
Copy code
try {
} catch (ArithmeticException e) {
return; // The return does not prevent the `finally` block from executing
} finally {
3. Nested try-catch-finally:
o You can nest try-catch-finally blocks inside one another, especially when dealing
with more complex logic that requires handling multiple exceptions or cleanup
steps at different stages of the process.
Example:
java
Copy code
try {
try {
} finally {
} catch (Exception e) {
} finally {
4. Exception Propagation:
o If an exception is not caught in the try block, and there's no corresponding catch
block, the exception is propagated to the caller of the method. However, the
finally block will still execute before the exception is passed up the call stack.
Flow of Execution:
• If no exception occurs, the code in the try block is executed, followed by the finally
block.
• If an exception occurs and is caught by a catch block, the catch block is executed,
followed by the finally block.
• If an exception occurs but is not caught by any catch block, the finally block will still
execute, and the exception is propagated further up the call stack.
Summary:
• The try-catch-finally mechanism in Java ensures that code can handle exceptions in a
controlled way while ensuring that critical cleanup tasks (like releasing resources) are
performed in the finally block, whether an exception occurs or not.
4o
You said:
java
Copy code
• ExceptionType: This is the type of the exception you want to throw (e.g.,
RuntimeException, IOException, or a custom exception).
• Exception message: This is a string message that provides details about the exception.
Throwing an Exception:
Example:
java
Copy code
try {
checkAge(15);
} catch (Exception e) {
// Throwing an exception
} else {
System.out.println("Age is valid.");
}
Output:
php
Copy code
Explanation:
• The checkAge method checks whether the provided age is 18 or older. If not, it throws an
Exception with a message, "Age must be 18 or older.".
• The throw statement creates and throws the new exception object.
• In the main method, this exception is caught by the catch block, which then prints the
exception message.
Example:
java
Copy code
Example:
java
Copy code
if (value < 0) {
throw new IllegalArgumentException("Negative value not allowed.");
If a method throws a checked exception, you must declare this in the method
signature using the throws keyword. This allows the calling code to know that it must
handle the exception or propagate it further.
Example:
java
Copy code
In this case, the method someMethod declares that it throws an IOException. Any
code calling this method must either handle the IOException using a try-catch block
or declare that it throws the exception itself.
You can also define your own custom exception class and throw it using throw.
Example:
java
Copy code
super(message);
}
public class CustomExceptionExample {
try {
validateAge(16);
} catch (InvalidAgeException e) {
} else {
System.out.println("Age is valid.");
Output:
php
Copy code
Key Points:
1. Checked exceptions: Must be either caught or declared using throws. If a method
throws a checked exception (like Exception, IOException, etc.), it must either handle it
or declare it with the throws clause.
2. Unchecked exceptions: These are typically subclasses of RuntimeException and do
not need to be declared or handled explicitly.
java
Copy code
try {
} catch (ArithmeticException e) {
if (b == 0) {
} else {
Output:
csharp
Copy code
Summary:
This mechanism helps you control error handling in a fine-grained manner, making
your program more robust and maintainable.
4o
You said:
Syntax of throws:
java
Copy code
// Method code
Key Points:
• throws keyword: Used in a method declaration to specify which exceptions the method
can throw.
• Checked Exceptions: If a method throws a checked exception, it must declare that
using throws.
• Unchecked Exceptions: throws is not mandatory for unchecked exceptions (i.e.,
subclasses of RuntimeException), but it can still be used for clarity.
Example of throws:
java
Copy code
import java.io.*;
try {
readFile("somefile.txt");
} catch (FileNotFoundException e) {
} catch (IOException e) {
System.out.println(line);
reader.close();
}
Explanation:
Checked exceptions are those that are checked at compile-time, and if your method
can throw any checked exception, you must either:
Example:
java
Copy code
Example:
java
Copy code
if (b == 0) {
System.out.println(a / b);
You can declare multiple exceptions that a method might throw by separating them
with commas.
Example:
java
Copy code
java
Copy code
method1();
} catch (Exception e) {
Output:
php
Copy code
throws vs throw:
• throws: Used in the method signature to declare that a method may throw one or more
exceptions.
java
Copy code
java
Copy code
Consider a method that connects to a database and performs some operations. The
method may throw several exceptions, such as SQLException for database errors
and IOException for input/output errors. These exceptions are declared using throws
so that the caller is aware of them and can handle them.
java
Copy code
try {
connectToDatabase();
}
}
Explanation:
• The method connectToDatabase declares that it might throw both SQLException and
IOException.
• In the main method, these exceptions are caught using a try-catch block.
Summary:
• throws is used in method declarations to indicate that the method might throw one or
more exceptions.
• Checked Exceptions (like IOException, SQLException): Must be declared using throws
or handled within the method.
• Unchecked Exceptions (like NullPointerException, ArithmeticException): Do not need
to be declared with throws, though you can do so for clarity.
• If a method declares a checked exception using throws, the caller must handle the
exception using a try-catch block or propagate it further by declaring throws in its own
method signature.
The throws keyword ensures that exceptions are properly handled or propagated,
making your code more robust and reliable.
4o
You said:
Let's create a custom exception called InvalidAgeException that checks if the user's
age is below 18.
Code:
java
Copy code
// Default constructor
public InvalidAgeException() {
super(message);
try {
} catch (InvalidAgeException e) {
}
// Method to validate age
} else {
Output:
csharp
Copy code
Explanation:
Code:
java
Copy code
// Default constructor
public DivideByZeroException() {
super(message);
try {
} catch (DivideByZeroException e) {
if (b == 0) {
} else {
Output:
csharp
Copy code
Explanation:
Key Points:
Code:
java
Copy code
public DataNotFoundException() {
super(message);
super(message, cause);
super(cause);
}
public class CustomExceptionExample {
try {
} catch (DataNotFoundException e) {
if (data == null) {
Output:
kotlin
Copy code
Explanation:
Summary:
• Custom exceptions in Java can be created by extending either the Exception class (for
checked exceptions) or RuntimeException class (for unchecked exceptions).
• Provide at least a default constructor and a constructor with a custom message.
• You can also provide additional constructors for passing a cause (Throwable) or both a
message and a cause.
• Custom exceptions help you provide specific, meaningful error messages and behaviors
tailored to your application's domain. This improves clarity and the handling of error
conditions within your code.