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

Module 5

Uploaded by

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

Module 5

Uploaded by

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

MODULE-5

1. Exceptions Handling: Exception types in java


In Java, exceptions are objects that represent errors or abnormal conditions that
occur during the execution of a program. Exception handling is done using the try-
catch mechanism, where potentially problematic code is enclosed in a try block,
and exceptions are handled in catch blocks.

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

Common Checked Exceptions:

• ClassNotFoundException: Thrown when trying to load a class that is not found.


• IOException: Thrown when an input/output operation fails or is interrupted.
• SQLException: Thrown when a database access error occurs.

2. Unchecked Exceptions (Runtime Exceptions)

• 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

Common Unchecked Exceptions:

• NullPointerException: Thrown when trying to access an object reference that is null.


• ArrayIndexOutOfBoundsException: Thrown when trying to access an invalid index of an
array.
• ArithmeticException: Thrown when an exceptional arithmetic condition occurs, such as
division by zero.
• IllegalArgumentException: Thrown when a method is passed an illegal or inappropriate
argument.
• ClassCastException: Thrown when an object is cast to a class of which it is not an
instance.

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.

Exception Class Hierarchy

Java exceptions are organized in a class hierarchy:

1. Throwable (Base class for all exceptions and errors)


o Exception (Base class for all exceptions)
▪ Checked Exceptions (e.g., IOException, SQLException)
▪ RuntimeException (e.g., NullPointerException,
ArrayIndexOutOfBoundsException)
o Error (e.g., OutOfMemoryError, StackOverflowError)

Custom Exceptions

Java allows creating user-defined or custom exceptions by extending the Exception


or RuntimeException class. This is useful for throwing specific business logic
exceptions.

java

Copy code

class MyCustomException extends Exception {

public MyCustomException(String message) {

super(message);

Handling Exceptions: try-catch block


java

Copy code

try {

// Code that might throw an exception

} catch (ExceptionType1 e) {

// Handle exception of type ExceptionType1

} catch (ExceptionType2 e) {

// Handle exception of type ExceptionType2

} finally {

// This block always executes, whether an exception is thrown or not

• try block: Wraps the code that might throw an exception.


• catch block: Handles the specific exception.
• finally block: Executes after the try and catch blocks, used for cleanup code (e.g.,
closing resources).

This is an overview of exception types and handling in Java, helping to manage errors
and maintain program flow.

4o

You said:

2. Exceptions Handling: Try…Catch…Finally


In Java, the try-catch-finally block is the primary mechanism used for handling
exceptions. It allows you to write code that may throw exceptions in a controlled
manner, catch and handle those exceptions, and optionally execute cleanup code
regardless of whether an exception was thrown or not.

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 {

// Code that may throw an exception

} catch (ExceptionType1 e) {

// Handle exception of type ExceptionType1

} catch (ExceptionType2 e) {

// Handle exception of type ExceptionType2

} finally {

// Code that will always execute (cleanup code)

Example of try-catch-finally:

java

Copy code

import java.io.*;

public class ExceptionExample {

public static void main(String[] args) {

FileReader file = null;

try {

file = new FileReader("nonexistentfile.txt");

char[] a = new char[50];


file.read(a); // Reading the file

System.out.println(a);

} catch (FileNotFoundException e) {

System.out.println("File not found: " + e.getMessage());

} catch (IOException e) {

System.out.println("An I/O error occurred: " + e.getMessage());

} finally {

// Cleanup code that will run regardless of exceptions

if (file != null) {

try {

file.close();

} catch (IOException e) {

System.out.println("Error closing the file: " + e.getMessage());

System.out.println("Execution completed, file closed.");

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).

Example showing the finally block still runs:

java

Copy code

try {

int result = 10 / 0; // This will throw ArithmeticException

} catch (ArithmeticException e) {

System.out.println("Exception caught: " + e.getMessage());

return; // The return does not prevent the `finally` block from executing

} finally {

System.out.println("This will always be printed.");

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 {

// Outer try block

try {

// Inner try block


} catch (Exception e) {

// Inner catch block

} finally {

// Inner finally block

} catch (Exception e) {

// Outer catch block

} finally {

// Outer finally block

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:

3. Exceptions Handling: Throw in java


In Java, the throw keyword is used to explicitly throw an exception from a method or
a block of code. When an exception is thrown using throw, the normal flow of the
program is disrupted, and control is transferred to the nearest matching catch block
or, if not caught, the program will terminate abnormally.
Syntax of throw:

java

Copy code

throw new ExceptionType("Exception message");

• 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

public class ThrowExample {

public static void main(String[] args) {

try {

checkAge(15);

} catch (Exception e) {

System.out.println("Caught Exception: " + e.getMessage());

public static void checkAge(int age) throws Exception {

if (age < 18) {

// Throwing an exception

throw new Exception("Age must be 18 or older.");

} else {

System.out.println("Age is valid.");
}

Output:

php

Copy code

Caught Exception: Age must be 18 or older.

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.

Key Points about throw:

1. Used to throw both checked and unchecked exceptions:


o Checked exceptions: Must be either handled with a try-catch block or declared
using the throws keyword in the method signature.
o Unchecked exceptions: These don't need to be declared or handled explicitly.
2. Custom exception messages:
o When creating an exception, you can pass a custom message to provide more
context about the error.

Example:

java

Copy code

throw new IllegalArgumentException("Invalid argument passed.");

3. Raising exceptions manually:


o The throw keyword allows the programmer to trigger an exception based on
certain conditions in the code.

Example:

java

Copy code

if (value < 0) {
throw new IllegalArgumentException("Negative value not allowed.");

4. Control flow interruption:


o When an exception is thrown using throw, the method's execution is
immediately interrupted, and control is passed to the nearest catch block that
can handle the exception.
o If the exception is not caught within the method, it propagates up the call stack.

Declaring Exceptions using throws:

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

public void someMethod() throws IOException {

throw new IOException("File could not be opened.");

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.

Example with Custom Exception:

You can also define your own custom exception class and throw it using throw.

Example:

java

Copy code

class InvalidAgeException extends Exception {

public InvalidAgeException(String message) {

super(message);

}
public class CustomExceptionExample {

public static void main(String[] args) {

try {

validateAge(16);

} catch (InvalidAgeException e) {

System.out.println("Caught Exception: " + e.getMessage());

static void validateAge(int age) throws InvalidAgeException {

if (age < 18) {

// Throwing custom exception

throw new InvalidAgeException("Age must be 18 or above.");

} else {

System.out.println("Age is valid.");

Output:

php

Copy code

Caught Exception: Age must be 18 or above.

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.

Example of Throwing a RuntimeException (Unchecked Exception):

java

Copy code

public class UncheckedExceptionExample {

public static void main(String[] args) {

try {

divide(5, 0); // Will throw ArithmeticException

} catch (ArithmeticException e) {

System.out.println("Caught Exception: " + e.getMessage());

static void divide(int a, int b) {

if (b == 0) {

// Throwing an unchecked exception

throw new ArithmeticException("Cannot divide by zero.");

} else {

System.out.println("Result: " + a / b);

Output:
csharp

Copy code

Caught Exception: Cannot divide by zero.

Summary:

• throw: Used to explicitly throw an exception in Java.


• throws: Used in method signatures to declare that the method may throw certain types
of exceptions (mainly checked exceptions).
• You can throw both checked and unchecked exceptions using throw.
• When an exception is thrown, normal flow of execution is interrupted, and control is
passed to the nearest catch block that handles the exception, or the exception
propagates up the call stack if uncaught.

This mechanism helps you control error handling in a fine-grained manner, making
your program more robust and maintainable.

4o

You said:

4.Exceptions Handling: Throws in java


In Java, the throws keyword is used in method signatures to indicate that a method
might throw one or more exceptions. It tells the caller of the method that the method
might throw certain exceptions, and it is the caller's responsibility to handle or
propagate them further. The throws clause is primarily used for checked
exceptions, which must be either handled or declared.

Syntax of throws:

java

Copy code

return_type methodName(parameters) throws ExceptionType1, ExceptionType2 {

// 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.*;

public class ThrowsExample {

public static void main(String[] args) {

try {

readFile("somefile.txt");

} catch (FileNotFoundException e) {

System.out.println("File not found: " + e.getMessage());

} catch (IOException e) {

System.out.println("An I/O error occurred: " + e.getMessage());

// Method that throws checked exceptions

public static void readFile(String fileName) throws FileNotFoundException,


IOException {

FileReader file = new FileReader(fileName); // May throw


FileNotFoundException

BufferedReader reader = new BufferedReader(file);

String line = reader.readLine(); // May throw IOException

System.out.println(line);

reader.close();
}

Explanation:

1. Method Declaration with throws:


o The readFile method declares that it throws FileNotFoundException and
IOException. This means the method might throw these exceptions during its
execution, and the caller must either handle them or propagate them further.
2. Handling the Exceptions:
o In the main method, the exceptions are caught using try-catch blocks. If the file
is not found, a FileNotFoundException is thrown, and if any I/O error occurs
while reading the file, an IOException is thrown.
3. Propagating Exceptions:
o If readFile method does not catch these exceptions internally, they are
propagated to the caller (main method) where they are handled.

Why Use throws?

• Checked Exceptions: In Java, checked exceptions must be declared in the method


signature using throws, or they must be caught inside the method. This provides a way
to ensure that errors are not ignored.
• Unchecked Exceptions: Methods are not required to declare unchecked exceptions
(subclasses of RuntimeException), but you can still use throws for documentation
purposes.

throws for Checked Exceptions:

Checked exceptions are those that are checked at compile-time, and if your method
can throw any checked exception, you must either:

1. Handle it using a try-catch block within the method.


2. Declare it using the throws clause in the method signature.

Example:

java

Copy code

public void myMethod() throws IOException {

throw new IOException("This is a checked exception");

throws for Unchecked Exceptions:

Unchecked exceptions (subclasses of RuntimeException like NullPointerException


or ArithmeticException) are not required to be declared with throws. However, you
can still use throws if you want to explicitly mention that your method might throw a
runtime exception.

Example:

java

Copy code

public void divide(int a, int b) throws ArithmeticException {

if (b == 0) {

throw new ArithmeticException("Cannot divide by zero");

System.out.println(a / b);

In this example, even though ArithmeticException is an unchecked exception, it's


declared with throws for clarity.

Declaring Multiple Exceptions with throws:

You can declare multiple exceptions that a method might throw by separating them
with commas.

Example:

java

Copy code

public void myMethod() throws IOException, SQLException {

// Code that may throw IOException or SQLException

Example: Propagating Exceptions with throws:

java

Copy code

public class PropagateExample {

public static void main(String[] args) {


try {

method1();

} catch (Exception e) {

System.out.println("Exception caught: " + e);

public static void method1() throws Exception {

method2(); // Propagating the exception to the caller

public static void method2() throws Exception {

throw new Exception("Error in method2"); // Throwing an exception

Output:

php

Copy code

Exception caught: java.lang.Exception: Error in method2

throws vs throw:

• throws: Used in the method signature to declare that a method may throw one or more
exceptions.

java

Copy code

public void method() throws IOException {

// Code that may throw IOException


}

• throw: Used within the method to actually throw an exception.

java

Copy code

throw new IOException("File not found");

Example of Using throws in Real-Life Scenario:

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

public class DatabaseExample {

public static void main(String[] args) {

try {

connectToDatabase();

} catch (SQLException | IOException e) {

System.out.println("Error: " + e.getMessage());

// Declaring multiple exceptions using throws

public static void connectToDatabase() throws SQLException, IOException {

// Code to connect to database

// If an error occurs, an exception will be thrown

throw new SQLException("Database connection error");

}
}

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:

5. Exceptions Handling: creating your own exception


subclasses in java
In Java, creating your own custom exception subclasses allows you to handle
specific error conditions in your application that may not be adequately represented
by the built-in exception types. You can extend either the Exception class for
checked exceptions or the RuntimeException class for unchecked exceptions.
This enables you to define meaningful, domain-specific exceptions with custom
messages and behaviors.

Steps to Create a Custom Exception:

1. Extend the Exception class or RuntimeException class.


o Checked Exceptions: Extend the Exception class.
o Unchecked Exceptions: Extend the RuntimeException class.
2. Provide constructors: Typically, you provide at least two constructors:
o A default constructor.
o A constructor that accepts a message or cause to describe the error.

Example: Creating a Custom Checked Exception

Let's create a custom exception called InvalidAgeException that checks if the user's
age is below 18.
Code:

java

Copy code

// Custom checked exception by extending Exception class

class InvalidAgeException extends Exception {

// Default constructor

public InvalidAgeException() {

super("Invalid age. Age must be 18 or above.");

// Constructor that accepts a custom error message

public InvalidAgeException(String message) {

super(message);

public class CustomCheckedExceptionExample {

public static void main(String[] args) {

try {

validateAge(16); // Passing age below 18

} catch (InvalidAgeException e) {

System.out.println("Caught Exception: " + e.getMessage());

}
// Method to validate age

public static void validateAge(int age) throws InvalidAgeException {

if (age < 18) {

// Throwing the custom checked exception

throw new InvalidAgeException("Age " + age + " is too young. Must be 18 or


older.");

} else {

System.out.println("Valid age: " + age);

Output:

csharp

Copy code

Caught Exception: Age 16 is too young. Must be 18 or older.

Explanation:

• InvalidAgeException: This custom exception extends Exception, making it a checked


exception.
• Constructors: It includes a default constructor and another constructor that accepts a
custom error message.
• validateAge method: If the provided age is less than 18, the method throws an
InvalidAgeException. The exception is caught in the main method.

Example: Creating a Custom Unchecked Exception

Now let's create a custom unchecked exception called DivideByZeroException to


handle cases where a division by zero occurs.

Code:

java

Copy code

// Custom unchecked exception by extending RuntimeException class


class DivideByZeroException extends RuntimeException {

// Default constructor

public DivideByZeroException() {

super("Division by zero is not allowed.");

// Constructor that accepts a custom error message

public DivideByZeroException(String message) {

super(message);

public class CustomUncheckedExceptionExample {

public static void main(String[] args) {

try {

divide(10, 0); // Division by zero

} catch (DivideByZeroException e) {

System.out.println("Caught Exception: " + e.getMessage());

// Method that performs division

public static void divide(int a, int b) {

if (b == 0) {

// Throwing the custom unchecked exception


throw new DivideByZeroException("You cannot divide " + a + " by zero.");

} else {

System.out.println("Result: " + (a / b));

Output:

csharp

Copy code

Caught Exception: You cannot divide 10 by zero.

Explanation:

• DivideByZeroException: This custom exception extends RuntimeException, making it


an unchecked exception.
• divide method: If the divisor is 0, the method throws a DivideByZeroException. The
exception is caught in the main method.

Key Points:

1. Checked vs. Unchecked Custom Exceptions:


o Checked exceptions: Extend the Exception class. These exceptions must be
either caught or declared in the method signature using throws.
o Unchecked exceptions: Extend the RuntimeException class. These exceptions
do not need to be declared or caught explicitly, but they can still be handled if
necessary.
2. Constructors in Custom Exceptions:
o Custom exception classes should provide constructors for flexibility:
▪ A default constructor to throw the exception with a default message.
▪ A custom constructor that accepts an error message to allow a more
descriptive exception.
3. Message Propagation:
o The super() call in the custom exception constructor passes the message to the
base exception class, which stores the message and makes it available via
getMessage().
4. When to Use Custom Exceptions:
o You can use custom exceptions to create more meaningful error messages and
behaviors that are specific to your application's logic. This improves readability,
debuggability, and maintenance of the code.

Example: Custom Exception with Multiple Constructors


You can also create custom exceptions with additional constructors, such as those
that accept a cause (Throwable) or both a message and a cause.

Code:

java

Copy code

class DataNotFoundException extends Exception {

// Constructor with default message

public DataNotFoundException() {

super("Data not found.");

// Constructor with custom message

public DataNotFoundException(String message) {

super(message);

// Constructor with custom message and cause

public DataNotFoundException(String message, Throwable cause) {

super(message, cause);

// Constructor with cause

public DataNotFoundException(Throwable cause) {

super(cause);

}
public class CustomExceptionExample {

public static void main(String[] args) {

try {

findData(null); // Passing null data

} catch (DataNotFoundException e) {

System.out.println("Caught Exception: " + e.getMessage());

public static void findData(String data) throws DataNotFoundException {

if (data == null) {

throw new DataNotFoundException("The provided data is null.");

System.out.println("Data found: " + data);

Output:

kotlin

Copy code

Caught Exception: The provided data is null.

Explanation:

• DataNotFoundException: This custom exception includes multiple constructors,


allowing flexibility in how it is thrown.
• The method findData checks if the data is null, and if it is, throws a
DataNotFoundException.

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.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy