OOP in Java Unit7

Download as pdf or txt
Download as pdf or txt
You are on page 1of 4

By: Manoj Sapkota, Nepal Polytechnic Institute

Unit-7: Exception Handling

Exceptions: An exception is an object that represents an error or an


unexpected event that occurs during the execution of a program. It disrupts
the normal flow of a program's instructions.

Types of exceptions: An exception can be categorized into three main types:


1. Checked Exceptions
2. Unchecked Exceptions
3. Errors

1. Checked Exceptions: These are the exceptions that are checked at compile-
time. The Java compiler checks if the program handles these exceptions,
otherwise it throws a compilation error.
Examples:
• IOException
• SQLException
• FileNotFoundException

2. Unchecked Exceptions: These are the exceptions that are checked at run-
time. They are also known as runtime exceptions.
Examples:
• NullPointerException
• ArrayIndexOutOfBoundException
• ArithmeticException

3. Errors: These are serious issues that are generally outside the control of the
application and represent problems that are not expected to be caught or
handled.
Examples:
• OutOfMemoryError
• StackOverflowError
• VirtualMachineError

Exception handling: Exception handling in Java is a mechanism to handle


runtime errors and maintain the normal flow of the program. It involves using
try, catch, throw, throws and finally constructs.
1. try: A block of code where exceptions can occur.

1
By: Manoj Sapkota, Nepal Polytechnic Institute

2. catch: A block of code that handles the exception.


3. finally: A block of code that executes regardless of an exception
occurring or not.
4. throw: Used to explicitly throw an exception.
5. throws: Declares exceptions that a method can throw.

A basic program example that illustrates the method of exception handling is


shown below:

public class Example {


public static void main(String[ ] args) {
try {
int divideByZero = 5 / 0; // This line will throw ArithmeticException;
} catch (ArithmeticException e) {
System.out.println("ArithmeticException caught: Division by zero.");
} finally {
System.out.println("This block always executes.");
}
}
}

Control Mechanism:
• If the exception does not occur, the catch block is skipped.
• If an exception occurs, the control is transferred to the catch block, and
then the finally block is executed.
• If there are multiple catch blocks, Java checks them in order and
executes the first one that matches the type of exception thrown.
• The finally block is optional, but it is a good practice to use it for
resource cleanup.

Using try and catch: The ‘try’ and ‘catch’ constructs are the fundamental
components of the exception handling mechanism. They are used to handle the
runtime errors and ensure that the normal flow of the program is maintained.

1. try block: The try block contains the code that might throw an exception.
Any code that might cause an exception should be placed inside this block. If
an exception occurs within this block, the flow of the program is disrupted, and
the control is passed to the corresponding catch block.

2
By: Manoj Sapkota, Nepal Polytechnic Institute

2. catch block: The catch block is used to handle the exception that is thrown
by the try block. There can be more than one catch blocks, each designed to
handle different types of exceptions. When an exception is thrown, the catch
block that matches the type of the exception is executed.
Example:
try {
int result = 10 / 0; // This will cause ArithmeticException
System.out.println("This line will not be executed.");
}
catch (ArithmeticException e) {
System.out.println("Exception caught: " + e.getMessage( ));
}

Using throw keyword: The throw keyword in Java is used to explicitly throw
an exception from a method or any block of code. This is generally used to
indicate that an unexpected or exceptional situation has occurred.
Working:
• When we use the throw keyword, we need to provide an instance of
Throwable (such as an Exception or Error).
• The control flow of the program stops at the point where the exception is
thrown, and the nearest matching catch block will handle the exception.

Example:
public class ThrowExample {
static void checkAge(int age) {
if (age < 18) {
//Throw an exception if age is less than 18
throw new IllegalArgumentException("Age must be >=18.");
} else {
System.out.println("Age is valid.");
}
}
public static void main(String[] args) {
try {
checkAge(15);
} catch (IllegalArgumentException e) {
System.out.println("Caught Exception: " + e.getMessage( ));
}
}
}

3
By: Manoj Sapkota, Nepal Polytechnic Institute

Using throws keyword: The throws keyword in Java is used in a method


declaration to indicate that the method may throw certain exceptions. It is
generally used when a method performs operations that might cause checked
exceptions, which need to be either caught or declared.

Example:
import java.io.*;
public class ThrowsExample {
public static void main(String[ ] args) {
try {
readFile("nonExistentFile.txt");
} catch (IOException e) {
System.out.println("Caught Exception: " + e.getMessage( ));
}
}

// Method declaration with throws keyword


static void readFile(String fileName) throws IOException {
FileReader file = new FileReader(fileName);
BufferedReader reader = new BufferedReader(file);
String line = reader.readLine( );
System.out.println(line);
reader.close();
}
}

You might also like