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

JAVA-Notes-Unit-2_Part 3

This document covers exception handling in Java, detailing the concepts of exceptions, their hierarchy, and the usage of keywords like try, catch, finally, throw, and throws. It explains the types of exceptions, including checked and unchecked exceptions, along with examples of each. Additionally, it provides code examples demonstrating how to implement exception handling in a Vehicle class.

Uploaded by

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

JAVA-Notes-Unit-2_Part 3

This document covers exception handling in Java, detailing the concepts of exceptions, their hierarchy, and the usage of keywords like try, catch, finally, throw, and throws. It explains the types of exceptions, including checked and unchecked exceptions, along with examples of each. Additionally, it provides code examples demonstrating how to implement exception handling in a Vehicle class.

Uploaded by

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

OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-II

Exception Handling PART-3


Concepts of exception handling, exception hierarchy, built in exceptions, usage of try,
catch, finally, throw, and throws, creating own exception sub classes.

Concepts of Exception Handling


An Exception is an unwanted or unexpected event that occurs during the
execution of a program (i.e., at runtime) and disrupts the normal flow of the
program’s instructions.

It occurs when something unexpected things happen, like accessing an invalid


index, dividing by zero, or trying to open a file that does not exist.

Exception handling in Java allows developers to manage runtime errors


effectively by using mechanisms like try-catch block, finally block, throwing
Exceptions, Custom Exception handling, etc.

Types of Java Exceptions

In Java, exceptions are categorized into two main types: checked exceptions and
unchecked exceptions. Additionally, there is a third category known as errors. Let's
delve into each of these types:

1. Checked Exception

2. Unchecked Exception
3. Error

B.Tech (CSE-DS)-II-II Sem Page 1


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-II

1. Checked Exceptions (Compile -time)


Checked exceptions are called compile-time exceptions because these
exceptions are checked at compile-time by the compiler.

Examples of Checked Exception are listed below:

1. ClassNotFoundException: Throws when the program tries to load a class at


runtime but the class is not found because its not present in the correct location or
it is missing from the project.
2. InterruptedException: Thrown when a thread is paused and another thread
interrupts it.
3. IOException: Throws when input/output operation fails
4. InstantiationException: Thrown when the program tries to create an object of a
class but fails because the class is abstract, an interface, or has no default
constructor.
5. SQLException: Throws when there’s an error with the database.
6. FileNotFoundException: Thrown when the program tries to open a file that
doesn’t exist

2. Unchecked Exceptions (Runtime Exceptions)


The unchecked exceptions are just opposite to the checked exceptions. The
compiler will not check these exceptions at compile time.

In simple words, if a program throws an unchecked exception, and even if we


didn’t handle or declare it, the program would not give a compilation error.

Examples of Unchecked Exception are listed below:

1. ArithmeticException: It is thrown when there’s an illegal math operation.


2. ClassCastException: It is thrown when you try to cast an object to a class it does
not belongs to.

B.Tech (CSE-DS)-II-II Sem Page 2


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-II

3. NullPointerException: It is thrown when you try to use a null object (e.g.


accessing its methods or fields)
4. ArrayIndexOutOfBoundsException: It occurs when we try to access an array
element with an invalid index.
5. ArrayStoreException: It happens when you store an object of the wrong type in
an array.
6. IllegalThreadStateException: It is thrown when a thread operation is not
allowed in its current state

3. Errors
Errors represent exceptional conditions that are not expected to be caught under
normal circumstances.

They are typically caused by issues outside the control of the application, such
as system failures or resource exhaustion. Errors are not meant to be caught or handled
by application code.

Examples of errors include:

1. OutOfMemoryError: It occurs when the Java Virtual Machine (JVM) cannot


allocate enough memory for the application.
2. StackOverflowError: It is thrown when the stack memory is exhausted due to
excessive recursion.
3. NoClassDefFoundError: It indicates that the JVM cannot find the definition of a
class that was available at compile-time.

B.Tech (CSE-DS)-II-II Sem Page 3


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-II

Hierarchy of Exceptions in Java


All exception and error types are subclasses of the class Throwable, which is
the base class of the hierarchy.

One branch is headed by Exception. This class is used for exceptional


conditions that user programs should catch. NullPointerException is an example of
such an exception.

Another branch, Error is used by the Java run-time system(JVM) to indicate


errors having to do with the run-time environment itself
(JRE). StackOverflowError is an example of such an error.

B.Tech (CSE-DS)-II-II Sem Page 4


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-II

Built-in Exceptions in Java


Built-in exceptions, also known as standard exceptions, are predefined exception
classes provided by Java.

These exceptions cover a wide range of common errors and exceptional


situations that can occur during program execution.

Built-in exceptions are part of the Java standard library and provide a
standardized way to handle common exceptional scenarios.

Built-In Exceptions can be further classified into two categories –

1. Checked Exceptions

2. Unchecked Exceptions

1. Checked Exceptions(Compiletime Exceptions)

Checked exceptions are called compile-time exceptions because these


exceptions are checked at compile-time by the compiler. Examples of Checked
Exception are listed below:

1. ClassNotFoundException: Throws when the program tries to load a class at


runtime but the class is not found because its not present in the correct location or
it is missing from the project.
2. InterruptedException: Thrown when a thread is paused and another thread
interrupts it.
3. IOException: Throws when input/output operation fails
4. InstantiationException: Thrown when the program tries to create an object of a
class but fails because the class is abstract, an interface, or has no default
constructor.
5. SQLException: Throws when there’s an error with the database.
6. FileNotFoundException: Thrown when the program tries to open a file that
doesn’t exist.

B.Tech (CSE-DS)-II-II Sem Page 5


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-II

2. Unchecked Exceptions (Runtime Exceptions)

The unchecked exceptions are just opposite to the checked exceptions. The
compiler will not check these exceptions at compile time. In simple words, if a
program throws an unchecked exception, and even if we didn’t handle or declare it,
the program would not give a compilation error. Examples of Unchecked Exception
are listed below:

1. ArithmeticException: It is thrown when there’s an illegal math operation.


2. ClassCastException: It is thrown when you try to cast an object to a class it
does not belongs to.
3. NullPointerException: It is thrown when you try to use a null object (e.g.
accessing its methods or fields)
4. ArrayIndexOutOfBoundsException: It occurs when we try to access an array
element with an invalid index.
5. ArrayStoreException: It happens when you store an object of the wrong type
in an array.
6. IllegalThreadStateException: It is thrown when a thread operation is not
allowed in its current state

Java Exception Class Methods


Following is the list of important methods available in the Throwable class.
S.No. Method & Description

public String getMessage()


1. Returns a detailed message about the exception that has occurred. This
message is initialized in the Throwable constructor.

2. public String toString()


Returns the name of the class concatenated with the result of getMessage().

public void printStackTrace()


3. Prints the result of toString() along with the stack trace to System.err, the
error output stream.

B.Tech (CSE-DS)-II-II Sem Page 6


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-II

Let’s go through an example where we use built-in exceptions, such as


IllegalArgumentException, ArithmeticException, and NullPointerException, in the
context of a Vehicle class.

Example: Vehicle Built-in Exceptions in Java

//Vehicle Built-in Exceptions in Java

package vehicle;

public class Vehicle


{
private String brand;
private int fuelLevel; // Fuel level in percentage (0 to 100)
private boolean isRunning;
// Constructor to initialize vehicle brand and fuel level
public Vehicle(String brand, int fuelLevel)
{
if (fuelLevel < 0 || fuelLevel > 100)
{
throw new IllegalArgumentException("Fuel level must be between 0 to 100.");
}
this.brand = brand;
this.fuelLevel = fuelLevel;
this.isRunning = false; // Initially the vehicle is not running
}
// Method to start the vehicle engine
public void startEngine()
{
if (fuelLevel <= 0)
{
throw new ArithmeticException("Cannot start the engine. Fuel level is zero.");
}
if (isRunning)
{
System.out.println(brand + " engine is already running.");
}

B.Tech (CSE-DS)-II-II Sem Page 7


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-II

else
{
isRunning = true;
System.out.println(brand + " engine started.");
}
}
// Method to stop the vehicle engine
public void stopEngine()
{
if (!isRunning)
{
throw new IllegalStateException("The vehicle engine is not running.");
}
isRunning = false;
System.out.println(brand + " engine stopped.");
}
// Method to refuel the vehicle
public void refuel(int amount)
{
if (amount <= 0)
{
throw new IllegalArgumentException("Refuel amount must be positive.");
}
fuelLevel += amount;
if (fuelLevel > 100)
{
fuelLevel = 100; // Fuel level cannot exceed 100%
}
System.out.println(brand + " refueled. Current fuel level: " + fuelLevel + "%");
}
// Method to drive the vehicle
public void drive()
{
if (!isRunning)
{
throw new IllegalStateException("The vehicle is not running. Start the engine first.");
}
System.out.println(brand + " is driving.");
}
}

B.Tech (CSE-DS)-II-II Sem Page 8


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-II

//Main.java
import vehicle.Vehicle;
public class Main
{
public static void main(String[] args)
{
try
{
// Create a new vehicle with a valid fuel level
Vehicle v1 = new Vehicle("Toyota", 50);

// Start the engine


v1.startEngine();
v1.drive();
// Attempt to start the engine again (already running)
v1.startEngine();
// Attempt to refuel with a negative value (invalid)
v1.refuel(-10);
}
catch (IllegalArgumentException e)
{
System.out.println("Error: " + e.getMessage());
}
catch (ArithmeticException e)
{
System.out.println("Error: " + e.getMessage());
}
catch (IllegalStateException e)
{
System.out.println("Error: " + e.getMessage());
}
catch (NullPointerException e)
{
System.out.println("Error: " + e.getMessage());
}

B.Tech (CSE-DS)-II-II Sem Page 9


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-II

// Simulate another scenario where vehicle is stopped


try
{
// Create another vehicle with zero fuel
Vehicle v2 = new Vehicle("Ford", 0);
// Attempt to start the engine without fuel
v2.startEngine();
}
catch (ArithmeticException e)
{
System.out.println("Error: " + e.getMessage());
}
}
}

Output:

B.Tech (CSE-DS)-II-II Sem Page 10


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-II

Usage of try, catch, finally, throw, and throws


In Java, exception handling involves the use of the try, catch, finally, throw, and
throws keywords.

This is where you place the code that might throw an


try block
exception.
catch block This block handles exceptions that occur in the try block.

This block always runs, regardless of whether an exception is


finally block
thrown or not, and is typically used for cleanup operations.

throw keyword Used to explicitly throw an exception.

Used in a method signature to declare that the method can


throws keyword
throw one or more exceptions.

1. try block

 A try block consists of all the doubtful statements that can throw exceptions.
 A try block cannot be executed on itself; it requires at least one catch block
or finally block.
 If an exception occurs, the control flows from the try-to-catch block.
 When an exception occurs in a try block, the appropriate exception object is
redirected to the catch block. This catch block handles the exception
according to its statements and continues the execution.

Syntax

try
{
//Doubtful Statements.
}

B.Tech (CSE-DS)-II-II Sem Page 11


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-II

2. catch block

 The catch block handles the exception raised in the try block.
 The catch block or blocks follow every try block.
 The catch block catches the thrown exception as its parameter and executes
the statements inside it.
 The declared exception must be the parent class exception, the generated
exception type in the exception class hierarchy, or a user-defined
exception.

Syntax

try
{
//Doubtful Statements.
}
catch(Exception e)
{
// code to handle exceptions
}

Multiple catch Blocks

We can use multiple catch statements for different kinds of exceptions that can
occur from a single block of code in the try block.

Syntax

try
{
// code to check exceptions
}
catch (exception1)
{
// code to handle the exception
}
catch (exception2)
{
// code to handle the exception
}

B.Tech (CSE-DS)-II-II Sem Page 12


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-II

3. finally block
The finally block in Java always executes even if there are no exceptions. This
is an optional block. It is used to execute important statements such as closing
statements, releasing resources, and releasing memory. There could be one final block
for every try block. This finally block executes after the try...catch block.

Syntax

try
{
//code
}
catch (ExceptionType1 e1)
{
// catch block
}
finally
{
// finally block always executes
}

4. throw Keyword

 The throw keyword is used to explicitly throw a checked or an unchecked


exception.
 The exception that is thrown needs to be of type Throwable or a subclass of
Throwable.
 We can also define our own set of conditions for which we can throw an
exception explicitly using the throw keyword.
 The program's execution flow stops immediately after the throw statement is
executed, and the nearest try block is checked to see if it has a catch
statement that matches the type of exception.

Syntax

throw new exception_class("error message");

B.Tech (CSE-DS)-II-II Sem Page 13


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-II

5. throws keyword

The throws keyword is used in the method signature to indicate that a method
in Java can throw particular exceptions. This notifies the method that it must manage
or propagate these exceptions to the caller.

Syntax

return_type method_name() throws exception_class_name


{
//method code
}

Here's an example of how each of these can be used in the context of a Vehicle class.

Example: try, catch, finally, throw, and throws in Java

// Custom unchecked exception for when the vehicle is already stopped


class VehicleAlreadyStoppedException extends RuntimeException
{
public VehicleAlreadyStoppedException(String message)
{
super(message);
}
}

// Custom checked exception for out of fuel error


class OutOfFuelException extends Exception
{
public OutOfFuelException(String message)
{
super(message);
}
}

B.Tech (CSE-DS)-II-II Sem Page 14


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-II

class Vehicle
{
private boolean isRunning = false;
private int fuelLevel = 10; // Fuel level out of 100
// Method to start the vehicle
public void start()
{
System.out.println("Vehicle is starting...");
isRunning = true;
}
// Method to stop the vehicle
public void stop()
{
if (!isRunning)
{
// Throw a custom unchecked exception if trying to stop an already stopped vehicle
throw new VehicleAlreadyStoppedException("Vehicle is already stopped.");
}
System.out.println("Vehicle is stopping...");
isRunning = false;
}
// Method to accelerate the vehicle
public void accelerate(int speed)
{
try
{
if (speed < 0)
{
throw new IllegalArgumentException("Speed cannot be negative.");
}
System.out.println("Accelerating to " + speed + " km/h...");
}
catch (IllegalArgumentException e)
{
System.out.println("Error while accelerating: " + e.getMessage());
}
finally
{
System.out.println("Acceleration attempt completed.");
}
}

B.Tech (CSE-DS)-II-II Sem Page 15


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-II

// Method to drive, might throw an OutOfFuelException


public void drive() throws OutOfFuelException
{
if (fuelLevel <= 0)
{
// Throw a custom checked exception if the vehicle is out of fuel
throw new OutOfFuelException("Out of fuel! Cannot drive.");
}
System.out.println("Vehicle is driving...");
fuelLevel -= 10; // Decrease fuel level by 10
}

public class VehicleTest


{
public static void main(String[] args)
{
Vehicle v = new Vehicle();

// Example 1: Using try, catch, finally


try
{
v.accelerate(-10); // Invalid speed, will throw IllegalArgumentException
}
catch (IllegalArgumentException e)
{
System.out.println("Caught exception in accelerate method: " + e.getMessage());
}
finally
{
System.out.println("Finally block executed for acceleration.");
}
// Example 2: Using throw to manually throw a custom unchecked exception
try
{
v.stop(); // This will stop the vehicle
v.stop(); // This will throw VehicleAlreadyStoppedException
}

B.Tech (CSE-DS)-II-II Sem Page 16


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-II

catch (VehicleAlreadyStoppedException e)
{
System.out.println("Caught exception in stop method: " + e.getMessage());
}

// Example 3: Using throws to declare a custom checked exception


try
{
v.drive();
v.drive(); // Might throw OutOfFuelException
}
catch (OutOfFuelException e)
{
System.out.println("Caught exception in drive method: " + e.getMessage());
}
}
}
Output:

B.Tech (CSE-DS)-II-II Sem Page 17


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-II

Creating own Exception sub Classes


You can create your own exceptions in Java. Keep the following points in mind
when writing your own exception classes.

 All exceptions must be a child of Throwable.


 If you want to create a checked exception that is automatically enforced you to
extend the Exception class.
 If you want to create a unchecked exception, you need to extend the
RuntimeException class.

We can define our own checked Exceptions class as below –

Syntax

class MyException extends Exception


{
Statements
}
You just need to extend the predefined Exception class to create your own checked
Exceptions.

We can define our own unchecked Exceptions class as below –

Syntax

class MyException extends RuntimeException

Statements

You just need to extend the predefined RuntimeException class to create your own
Exception.

B.Tech (CSE-DS)-II-II Sem Page 18


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-II

// Custom unchecked exception for when the vehicle is already stopped

class VehicleAlreadyStoppedException extends RuntimeException


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

// Custom checked exception for out of fuel error

class OutOfFuelException extends Exception


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

class Vehicle
{
private boolean isRunning = true;
private int fuelLevel = 10; // Fuel level out of 100

// Method to stop the vehicle


public void stop()
{
if (!isRunning)
{
// Throw a custom unchecked exception if trying to stop an already stopped vehicle
throw new VehicleAlreadyStoppedException("Vehicle is already stopped.");
}
System.out.println("Vehicle is stopping...");
isRunning = false;
}

B.Tech (CSE-DS)-II-II Sem Page 19


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-II

// Method to drive, might throw an OutOfFuelException


public void drive() throws OutOfFuelException
{
if (fuelLevel <= 0)
{
// Throw a custom checked exception if the vehicle is out of fuel
throw new OutOfFuelException("Out of fuel! Cannot drive.");
}
System.out.println("Vehicle is driving...");
fuelLevel -= 10; // Decrease fuel level by 10
}
}

public class VehicleTestCustomEx


{
public static void main(String[] args)
{
Vehicle v = new Vehicle();

//Using throw to manually throw a custom unchecked exception


try
{
v.stop(); // This will stop the vehicle
v.stop(); // This will throw VehicleAlreadyStoppedException
}
catch (VehicleAlreadyStoppedException e)
{
System.out.println("Caught exception in stop method: " + e.getMessage());
}

//Using throws to declare a custom checked exception


try
{
v.drive();
v.drive(); // Might throw OutOfFuelException
}

B.Tech (CSE-DS)-II-II Sem Page 20


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-II

catch (OutOfFuelException e)
{
System.out.println("Caught exception in drive method: " + e.getMessage());
}
}
}

B.Tech (CSE-DS)-II-II Sem Page 21

You might also like