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

Lecture 14 - Exception handling

The document explains the fundamentals of exception handling in Java, detailing how exceptions disrupt program flow and can be managed using try, catch, and finally blocks. It distinguishes between caught exceptions, which are checked at compile time, and uncaught exceptions, which are checked at runtime, providing examples of each. Additionally, it covers the use of multiple catch clauses, nested try-catch blocks, and the throw keyword for manually throwing exceptions.

Uploaded by

alfredjoso847
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Lecture 14 - Exception handling

The document explains the fundamentals of exception handling in Java, detailing how exceptions disrupt program flow and can be managed using try, catch, and finally blocks. It distinguishes between caught exceptions, which are checked at compile time, and uncaught exceptions, which are checked at runtime, providing examples of each. Additionally, it covers the use of multiple catch clauses, nested try-catch blocks, and the throw keyword for manually throwing exceptions.

Uploaded by

alfredjoso847
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

Fundamentals of Exception handling

● Exception handling is a mechanism in Java that allows programmers to deal


with runtime errors and other exceptional conditions that can occur during
program execution.
● An exception is an event that disrupts the normal flow of a program and
requires special handling to prevent the program from crashing or behaving
incorrectly.
● In Java, an exception is represented by an object that contains information
about the error, including its type, message, and stack trace.
● When an exception occurs, Java creates an exception object and throws it,
which means it is passed to the nearest code block that can handle it.
● To handle exceptions in Java, programmers can use a combination of the try,
catch, and finally blocks. The basic syntax of exception handling in Java is as
follows:

try {
// code that may throw an exception
} catch (ExceptionType1 e1) {
// code to handle exception of type ExceptionType1
} catch (ExceptionType2 e2) {
// code to handle exception of type ExceptionType2
} finally {
// code that is always executed, regardless of whether an exception was
thrown
}

● The code that may throw an exception is enclosed in the try block.
● If an exception is thrown, Java looks for a catch block that matches the type
of the exception.
● If a matching catch block is found, the code inside that block is executed to
handle the exception.

1
● If no matching catch block is found, the exception is passed up to the next
level of the program's call stack, where it may be handled by another catch
block or cause the program to crash.
● The finally block is used to specify code that should be executed regardless
of whether an exception was thrown or caught.
● This block is commonly used to release resources such as files or network
connections that were opened in the try block.

Types of Exceptions
● In Java, there are two main types of exceptions: caught exceptions and
uncaught exceptions.
● All exceptions in Java are subclasses of the Exception class, which is the root
class for all exceptions. There is also a subclass of Exception called
RuntimeException, which is the root class for all uncaught exceptions.

2
1. Caught exceptions:
○ Caught exceptions are the exceptions that the compiler checks for at
compile time.
○ They are typically related to I/O, network, and database operations
that can throw exceptions.
○ caught exceptions are handled by either catching them or declaring
them in the method signature with the throws keyword.
○ If a method throws a caught exception, the calling method must
handle or re-throw it.
○ Examples of caught exceptions include:
■ IOException: occurs when an I/O operation fails, such as
reading or writing to a file or network socket.
■ SQLException: occurs when a database access error occurs,
such as a connection failure or SQL syntax error.
■ InterruptedException: occurs when a thread is interrupted while
waiting, sleeping, or performing another blocking operation.

2. Uncaught exceptions:
○ Uncaught exceptions are the exceptions that the compiler checks for
at runtime.
○ They typically occur due to programming errors such as null pointer
exceptions or arithmetic exceptions.
○ Uncaught exceptions are not required to be caught or declared with
the throws keyword.
○ Examples of uncaught exceptions include:
■ NullPointerException: occurs when trying to call a method or
access a property of a null object.
■ ArithmeticException: occurs when performing an arithmetic
operation with invalid operands, such as dividing by zero.

3
■ ArrayIndexOutOfBoundsException: occurs when trying to
access an array element with an invalid index.

Using try and catch


● Let's say we have a program that reads input from the user and converts it to
an integer.
● If the user enters invalid input (e.g., a non-numeric value), an exception will
be thrown.
● We can use a try-catch block to handle this exception and provide a friendly
error message to the user.

import java.util.Scanner;

public class UserInput {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

try {
System.out.print("Enter an integer: ");
int num = scanner.nextInt();
System.out.println("You entered: " + num);
} catch (Exception e) {
System.out.println("Invalid input. Please enter an integer.");
}

scanner.close();
}
}

● In this example, we use a try-catch block to handle any exceptions that may
be thrown when calling scanner.nextInt().
● If the user enters invalid input (e.g., a non-numeric value), the catch block is
executed and a friendly error message is displayed.

4
● Without the try-catch block, the program would crash with an unhandled
exception if the user entered invalid input.
● The try-catch block allows us to gracefully handle the exception and provide
a better user experience.

Multiple catch clauses


● You can use multiple catch clauses to handle different types of exceptions
that may be thrown by a try block.
● This allows you to provide specific error handling for different types of
exceptions, rather than using a catch-all Exception clause.

try {
// some code that may throw exceptions
} catch (IOException e) {
// handle IOException
} catch (NullPointerException e) {
// handle NullPointerException
} catch (Exception e) {
// handle any other exceptions
}

● The try block contains some code that may throw exceptions.
● If an IOException is thrown, the first catch block will handle it.
● If a NullPointerException is thrown, the second catch block will handle it.
● If any other type of exception is thrown, the last catch block will handle it.

5
Nested try and catch blocks
● It is possible to have nested try-catch blocks. This means that you can have a
try-catch block inside another try block's try or catch block.

try {
// some code that may throw an exception
try {
// some code that may also throw an exception
} catch (Exception e) {
// handle the inner exception
}
} catch (Exception e) {
// handle the outer exception
}

● In this example, the outer try block may throw an exception, and if it does, it
will be caught by the outer catch block.
● The inner try block may also throw an exception, and if it does, it will be
caught by the inner catch block.
● If the inner catch block handles the exception, then the program will continue
to execute normally.
● However, if the inner catch block does not handle the exception, then it will
be propagated to the outer catch block.
● Using nested try-catch blocks can be useful when you want to handle
different types of exceptions in different ways, depending on where they
occur in the code.
● You should use them judiciously, as too many levels of nesting can make the
code difficult to read and understand.

6
Using throw
● The throw keyword is used to manually throw an exception.
● When you throw an exception, you are basically indicating that something
unexpected or erroneous has occurred in your code.
● Consider this example of manually throwing an exception:

public class Calculator {


public static void main(String[] args) {
try {
int result = divide(10, 0);
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Error: " + e.getMessage());
}
}

public static int divide(int dividend, int divisor) throws


ArithmeticException {
if (divisor == 0) {
throw new ArithmeticException("Cannot divide by zero.");
}
return dividend / divisor;
}
}

● In this example, we have a Calculator class with a main method and a divide
method.
● The divide method takes two integers as parameters and performs division.
Before performing the division, it checks if the divisor is zero.
● If the divisor is zero, it throws an ArithmeticException with an appropriate
error message using the throw keyword.
● In the main method, we call the divide method with arguments 10 and 0.

7
● Since dividing by zero is an invalid operation, the divide method throws an
ArithmeticException.
● We surround the method call with a try-catch block to catch the exception. If
the exception occurs, we print an error message.
● By declaring throws ArithmeticException in the divide method signature, we
are indicating to the caller (in this case, the main method) that it needs to
handle or propagate this exception.
● In this example, the main method chooses to handle the exception by
catching it and displaying an error message.
● Note that the ArithmeticException in this example is an uncaught exception,
so it does not need to be explicitly declared in the throws clause.

You might also like