0% found this document useful (0 votes)
3 views15 pages

Chapter 8

Chapter 8 of 'Object Oriented Programming With JAVA' discusses exception handling in Java, explaining the concept of exceptions as unexpected events that disrupt program flow due to runtime errors. It outlines the mechanisms for handling exceptions, including try-catch blocks, the differences between checked and unchecked exceptions, and the JVM's reaction to exceptions. The chapter emphasizes the importance of effective exception handling to prevent application crashes and improve user experience.

Uploaded by

sapna842004
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)
3 views15 pages

Chapter 8

Chapter 8 of 'Object Oriented Programming With JAVA' discusses exception handling in Java, explaining the concept of exceptions as unexpected events that disrupt program flow due to runtime errors. It outlines the mechanisms for handling exceptions, including try-catch blocks, the differences between checked and unchecked exceptions, and the JVM's reaction to exceptions. The chapter emphasizes the importance of effective exception handling to prevent application crashes and improve user experience.

Uploaded by

sapna842004
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/ 15

Object Oriented Programming With JAVA

Chapter-8

Excep on Handling

The Idea Behind Exception


An exception is an unexpected event that disrupts the normal flow of a program,
often due to runtime errors such as division by
Idea behind Excep on
zero, accessing an invalid array index, or
Java Excep on
working with a null reference. These errors
 Handling Excep ons
 JVM Reac on to Excep on occur during program execution and can be
Excep on handling managed to maintain the normal flow until
Error Vs Excep on completion. This process is called exception
Try-Catch Block handling.
 Nested Try Catch
 Throw Keyword Understanding Java Exceptions
 Throws Keyword In Java, exceptions are managed using
Throw vs Throws a robust mechanism that involves try-catch-
Crea ng custom Excep on finally blocks, allowing the program to continue
Difference between final, finally running despite errors. Effective exception
and finalize method
handling prevents abrupt program termination
and provides meaningful error messages to users.
some examples of Java exception classes are ClassNotFoundException, IOException,
SQLException, RuntimeException

Why Handle Exceptions?

Java developers can handle exceptions to ensure the program does not terminate
abruptly. Users should receive a meaningful error message instead. For instance, when
writing a division program, if a user divides by zero, an exception is thrown due to the
undefined result. By handling this exception, we can prevent the program from crashing.

Example:
import java.util.Scanner;
public class MyProg {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the dividend: ");
int a = scanner.nextInt();
System.out.print("Enter the divisor: ");
int b = scanner.nextInt();
try {
int result = a / b;
Object Oriented Programming With JAVA
System.out.println("The result is: " + result);
} catch (ArithmeticException e) {
System.out.println("Error: Division by zero is not allowed.");
}
}
}
Output:

In this example, if the user enters zero as the divisor, the program catches the
ArithmeticException and displays an error message instead of terminating unexpectedly.

Benefits -Proper exception handling aids in:


- Preventing application crashes
- Improving debugging and issue resolution
- Identifying and fixing issues efficiently

Java's exception handling framework is built on the java.lang.Throwable class, which is the
root of the exception hierarchy. This class has two main subclasses: Exception and Error,
providing a structured approach to managing program errors.

JVM's Reaction to an Exception


The Java Virtual Machine (JVM) efficiently handles exceptions through a predefined set
of steps. Here's how the JVM manages exceptions during runtime:
1. Normal Execution (No Exception)- When a program runs smoothly without any
exceptions, the JVM processes the code sequentially, ensuring the execution completes
without any issues. This seamless execution from start to finish signifies successful program
operations.
Object Oriented Programming With JAVA
2. When an Exception Occurs- When an exception occurs, the JVM halts execution at the
error's location. It then searches for a corresponding catch block within the method and
manages the exception if a suitable catch block is found. If no catch block is present, the
JVM proceeds with stack unwinding by checking the calling method. If the exception
remains unhandled, the JVM prints an error message and terminates the program.
3. When Exception is NOT Handled- If no catch block addresses an exception anywhere in
the program, the JVM immediately halts execution. It then displays an error message,
known as the Exception Stack Trace, highlighting where the error occurred before
terminating the program.
4. JVM's Stack Unwinding Process -When an exception lacks handling in the current
method, the JVM propagates it up the call stack. This stack unwinding approach ensures
the exception is addressed. If no method in the call chain handles the exception, the
program is terminated by the JVM.
5. JVM's Default Exception Handler- For uncaught exceptions, the JVM's default exception
handler steps in to print a detailed exception description that includes the exception's
name and a method call stack trace before terminating the program.
6. JVM's Reaction with throws Keyword- If a method declares an exception using the
'throws' keyword without handling it, the calling method must take responsibility for
managing the exception. Failing to do so results in program termination by the JVM.
7. JVM’s Reaction with finally Block- Regardless of exceptions, the JVM always executes
the 'finally' block before terminating the program. This ensures that any cleanup or
mandatory code operations are completed without fail.
Understanding how the JVM handles exceptions ensures smoother program development
and enhances your ability to manage errors effectively in Java applications.

Exception Handling in Java


Java offers a powerful way to manage errors through try-catch-finally blocks, which
are essential for maintaining an application’s normal flow. Exception handling is crucial
because exceptions can disrupt this flow. Java exceptions are generally categorized into two
types: checked and unchecked exceptions, with errors being a subtype of unchecked
exceptions. According to Sun Microsystems, exceptions in Java are divided into three
categories:

1. Checked Exception
2. Unchecked Exception
3. Error

Understanding these categories is key for effective Java programming and ensuring that
your applications run smoothly.
1. Checked Exception: Checked exceptions in Java are exceptions that are verified at
compile-time. This means that if a method may throw a checked exception, it is required to
either handle it using a try-catch block or declare it using the throws keyword. Failing to do
so will result in a compilation error. Checked exceptions are classes that extend the
Throwable class, excluding RuntimeException and Error. Common examples of checked
exceptions include IOException and SQLException. Here are a few other checked exceptions.
Object Oriented Programming With JAVA

checked Exception Meaning


ClassNotFoundException This occurs when the Java Virtual Machine (JVM) or a
classLoader tries to load a class that doesn’t exist in the
specified classpath.
CloneNotSupportedException You attempted to clone an object that does not implement
the `Cloneable` interface.
NoSuchFieldException You’re trying to access a field that does not exist in the
specified class.
NoSuchMethodException This error indicates that the method you’re trying to call
doesn’t exist.
IllegalAccessException You're attempting to access a class or member that the
current context cannot invoke.
InterruptedException This happens when one thread is interrupted by another
thread.
InstantiationException You're trying to create an instance of an abstract class or
interface.

Let’s take an example to read a file contents.


import java.io. *;
class MyProg {
public static void main(String args[]) throws IOException
{
FileInputStream s = null;
s = new FileInputStream("c:/myfile.txt");
int k;
while ((k = s.read() ) != -1)
{
System.out.print((char)k);
}
s.close();
}
}
Output:
Object Oriented Programming With JAVA

The method we previously employed is far from ideal for handling exceptions. It is
important to follow best practices in exception handling to ensure clarity and ease of
understanding. Each exception should be accompanied by a meaningful message, making it
easier for users to comprehend the error. Here's how the code should look for better exception
handling:
import java.io. *;
class MyProg {
public static void main(String args[])
{
FileInputStream s = null;
try{
s = new FileInputStream("MyProg.java");
} catch (FileNotFoundException e) {
System.out.println("file not found at the given location");
}
int k;
try {
while ((k = s.read() ) != -1)
{
System.out.print((char)k);
}
s.close();
} catch (IOException e) {
System.out.println("I/O exception occurred Error code: "+e);
}
}
}
Output:
Object Oriented Programming With JAVA

2.Unchecked Exception: Unchecked exceptions, which are not validated during


compile time, do not cause compilation errors even if they are neither handled nor declared.
Typically, these exceptions arise from incorrect data input by users during program
interactions. All unchecked exceptions are direct subclasses of the RuntimeException class. In
Java, classes extending RuntimeException are considered unchecked exceptions.

Unchecked Exception Meaning


ArrayIndexOutOfBoundException This error happens when you try to access elements
outside an array's bounds. For instance, with an array
containing five elements, accessing the 10th element is
invalid.
ArrayStoreException Assigning a value to an array element with an
incompatible data type leads to errors.
NegativeArraySizeException Defining an array with a negative size is not permissible
and will cause an exception.
IndexOutOfBoundException Using an index value beyond the allowed limit of an
array results in a boundary error.
ArithmaticException Attempting to divide any number by zero is undefined
and triggers a division by zero exception.
ClassCastException Errors arise when trying to cast a variable to an
incompatible type.
IllegalArgumentException Providing inappropriate arguments for a method call
causes this error.
IllegalMonitorStateException waiting on a thread that is not locked will prompt an
error.
Object Oriented Programming With JAVA
Unchecked Exception Meaning
IllegalStateException Operations that do not match the current application or
environment state may fail.
IllegalThreadStateException If an operation isn't compatible with the current thread
state, expect an error.
StringIndexOutOfBound Attempt to access index outside the bounds
SecurityException Attempting unauthorized access or actions results in
security errors.
NullPointerException Using a null reference for method calls or operations
triggers exceptions.
NumberFormatException Errors occur when converting a string into an invalid
numeric format.
UnsupportedOperationException Engaging an operation not supported by the
environment or context will cause issues.

Let’s understand this with an example:


class MyProg {
public static void main (String args[])
{
int arr[] ={1,2,3,4,5};
System.out.println(arr[6]);
}
}
Here our array has only 5 elements but we are trying to access the value of 7th element. It
should throw ArrayIndexOutOfBoundsException we have handled this exception.
class MyProg {
public static void main(String args[]) {
try{
int arr[] ={1,2,3,4,5};
System.out.println(arr[7]);
}
catch (ArrayIndexOutOfBoundsException e) {
System.out.println("The required index does not exist in array."+e);
}
}
}

Output:
Object Oriented Programming With JAVA
Difference Between Checked and Unchecked Exception

Checked Exception Unchecked Exception


Exception which are checked at compile time Exceptions whose handling is not verified
called checked exception. during compile time.
When a method throws a checked exception, it During runtime, the Java Virtual Machine
is required to either handle the exception within (JVM) handles these exceptions using the try
the method or specify the exception using the and catch blocks.
`throws` keyword in its declaration. This ensures
proper error handling and enhances the
reliability of your code.

3. Error vs exception

In the realm of programming, understanding the distinction between errors and


exceptions is crucial. Errors signify a significant issue that falls outside the programmer's
control, often pointing to critical system failures such as disk crashes or resource unavailability.
Unlike exceptions, errors are not caused by incorrect user input and are typically irrecoverable.
Common examples include AssertionError, OutOfMemoryError, and VirtualMachineError.

Conversely, exceptions are runtime events triggered by issues like incorrect user data
or flawed programming logic. These can be managed by the programmer, who can implement
corrective measures. Java's java.lang package contains numerous exception classes, with many
falling under the umbrella of RuntimeException. Since java.lang is automatically imported into
all Java programs, exceptions derived from RuntimeException are readily accessible to
developers. By effectively handling exceptions, programmers can enhance the robustness and
reliability of their Java applications.
try- In Java, a try block is used to encapsulate code that may potentially throw an
exception. By surrounding this code within a try block, you prepare for handling possible errors
that could disrupt the program’s flow. If an exception is thrown, it is caught by the appropriate
catch block. Remember, a try block must always be paired with either a catch block or a finally
block within a method to properly manage exceptions.
Syntax: try{
// Code that may cause an exception
}
catch- In programming, the catch block is designed to manage exceptions thrown by
the try block. To efficiently address various types of exceptions, you can utilize multiple catch
blocks.
Syntax: catch (Exception e)
{
// Handle the exception
}
Object Oriented Programming With JAVA

finally- In Java programming, the "finally" block is essential for executing code that
must run, regardless of whether an exception was thrown or caught. This block is primarily
used for resource cleanup, such as closing connections and streams. A key feature of the Java
"finally" block is that it always executes, regardless of how the preceding try or catch blocks
are handled. As such, it is crucial for ensuring the consistent release of resources in your Java
applications.
Syntax:
try {
// Code that may cause an exception
} catch (ExceptionType e) {
// Handle the exception
} finally {
// (Optional) Block that always executes
}
Object Oriented Programming With JAVA
1. A finally block must be directly associated with a try block—you cannot have a finally
block without including a try block. It's ideal to place statements here that should always be
executed, regardless of what occurs in the try block.

2. While the finally block is optional, remember that a try-catch block is often sufficient
for handling exceptions. However, when included, a finally block will always run after the try
block completes.

3. Under normal circumstances, when no exceptions are thrown in the try block, the
finally block executes immediately afterwards. In the event of an exception, the catch block
executes first, followed by the finally block.

4. Exceptions that occur within the finally block behave just like any other exception,
potentially altering the program's flow.

5. The statements within a finally block execute even if the try block contains control
transfer statements like return, break, or continue.
The basic exception handling example as
public class MyProg{
public static void main (String [] args) {
try {
int result = 10 / 0; // This will throw ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Caught exception: " + e.getMessage());
} finally {
System.out.println("Finally block executed.");
}
}
}
Output:

When an unhandled exception occurs, the program terminates and displays a system-
generated error message to the user. Unfortunately, these messages are often not user-
friendly, making it difficult for users to understand the problem. To address this, programmers
handle exceptions and display clear, user-friendly error messages instead. By doing so, users
can easily identify and rectify the issue, as exceptions usually stem from incorrect data entry.
Nested try catch block
In programming, when a try-catch block is placed within another try block, it is referred
to as a nested try-catch block. If an exception arises within the inner try block and there isn't
a corresponding catch handler, the outer try block's catch handlers are checked. If a match is
found, the relevant catch block executes to handle the exception. However, if neither the inner
Object Oriented Programming With JAVA
nor outer catch blocks can handle the exception, a system-generated error message is
displayed, similar to what happens when exceptions are not handled at all.
Syntax:
try {
statement 1;
statement 2;
try { //try-catch block inside another try block
statement 3;
statement 4;
try { //try-catch block inside nested try block
statement 5;
statement 6;
}
catch(Exception e2) {
//Exception Message
}
}
catch(Exception e1) {
//Exception Message
}
}
catch(Exception e3) {//catch of Main(parent) try block
//Exception Message
}
Example:
class MyProg{
public static void main(String args[]){
//Parent try block
try{
try{//Child try block1
int b =30/0;
System.out.println("Inside block1"+b);
}
catch(ArithmeticException e1){
System.out.println("Exception: e1");
}
try{ //Child try block2
int b =49/0;
System.out.println(“Inside block2”+b);
}
catch(ArrayIndexOutOfBoundsException e2){
System.out.println("Exception: e2");
}
System.out.println("Just other statement");
}
Object Oriented Programming With JAVA
catch(ArithmeticException e3){
System.out.println("Arithmetic Exception Inside parent try catch block");
}
catch(ArrayIndexOutOfBoundsException e4){
System.out.println("ArrayIndexOutOfBoundsException Inside parent try catch
block");
}
catch(Exception e5){
System.out.println("Exception Inside parent try catch block");
}
}
}
Output:

throw- The Java throw keyword is essential for explicitly throwing exceptions within
your code. Whether you need to throw a checked or unchecked exception, the throw keyword
allows for this flexibility. It's particularly useful for generating custom exceptions, enabling you
to throw user-defined or customized exception objects directly to the Java Virtual Machine
(JVM). This functionality makes it a crucial tool for developers aiming to enhance error handling
and create more robust Java applications.
Syntax: throw exception;
Example:
class MyProg {
static void checkEligible(int age) {
if (age < 18)
throw new ArithmeticException("You are not eligible to vote");
else
System.out.println("You are eligible to vote");
}
public static void main(String[] args) {
checkEligible(14);
}
}
Output:

throws- In Java programming, the throws keyword is used in method signatures to


declare potential exceptions that might occur during the execution of a method. While it
doesn't actively throw an exception, it signals to developers that there might be exceptions
that need to be addressed, encouraging them to implement appropriate exception handling
code to maintain the normal flow of the application.
Object Oriented Programming With JAVA

Exception Handling is crucial for managing checked exceptions. However, for unchecked
exceptions like NullPointerException, programmers should conduct pre-execution checks to
prevent potential issues. By using the `throws` keyword, we ensure that any exceptions are
passed to the Java Virtual Machine (JVM) for further handling.
Syntax:
return_type method_name() throws exception_class_name{
//method code
}
Example:
import java.io.IOException;
class MyProg{
void disp()throws IOException{
throw new IOException("error in output");//checked exception
}
void input() throws IOException{
disp();
}
void print(){
try{
input() ;
}catch(Exception e){
System.out.println("exception handled manually");
}
}
public static void main(String []args){
MyProg obj=new MyProg();
obj.print();
System.out.println("program working normally");
}
}
Output:

Throw vs throws
Throw Throws
Java throw keyword is used to Java throws keyword is used to declare an
1
explicitly throw an exception. exception.
Checked exception cannot be Checked exception can be propagated
2
propagated using throw only. with throws.

3 it is followed by an instance. it is followed by class.

4 it is used within the method. it is used with the method signature.


Object Oriented Programming With JAVA
Throw Throws
You cannot throw multiple You can declare multiple exceptions e.g.
5 exceptions. void, public, IOException, SQLException.

Crea ng Custom Excep ons

Java allows creating user-defined exceptions. We can create our own exception by
extending exception class. The throw and throws keywords are used while implementing user
defined exceptions
Example:
class AgeException extends Exception {
AgeException(String message) {
super(message);
}
}
public class MyProg{
static void validateAge(int age) throws AgeException {
if (age < 18) {
throw new AgeException("Age must be 18 or above.");
} else {
System.out.println("Valid age.");
}
}
public static void main(String[] args) {
try {
validateAge(16);
} catch (AgeException e) {
System.out.println(e.getMessage());
}
}
}
Output:

Final
final is a keyword used to apply restrictions on class, method and variables. final class can’t be
inherited, final method can’t be overridden and final variable value can’t be changed.

example
class MyProg{
public static void main(String[] args){
final int x=10;
x=20;//Compile Time Error will occurred
Object Oriented Programming With JAVA
}
}
Output:

finally
finally, is the part of try-catch block.it will be executed whether exception is handled or not.it
is optional part with try. It is a block of code used with try and catch.

example
class MyProg{
public static void main(String[] args){
try{
int x=50;
}catch(Exception e){
System.out.println(e);
}finally{
System.out.println("finally block is executed");
}
}
}
Output:

finalize
finalize is a method. finalize is used to perform cleanup processing just before object is
garbage collected.
example
class MyProg{
public void finalize(){
System.out.println("finalize method called");
}
public static void main(String[] args){
MyProg f1=new MyProg ();
MyProg f2=new MyProg ();
f1=null;
f2=null;
System.gc();
}
}
Output:

You might also like