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

UNIT 5

Unit 6 focuses on exception handling in programming, particularly in Java, covering types of exceptions, the exception class hierarchy, and keywords used in exception handling. It explains the importance of handling exceptions to maintain program stability and readability, detailing checked, unchecked exceptions, and errors. The unit also introduces the try-catch mechanism for managing exceptions and emphasizes the role of the Throwable class in Java's exception handling framework.

Uploaded by

amanuel
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 views

UNIT 5

Unit 6 focuses on exception handling in programming, particularly in Java, covering types of exceptions, the exception class hierarchy, and keywords used in exception handling. It explains the importance of handling exceptions to maintain program stability and readability, detailing checked, unchecked exceptions, and errors. The unit also introduces the try-catch mechanism for managing exceptions and emphasizes the role of the Throwable class in Java's exception handling framework.

Uploaded by

amanuel
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/ 20

UNIT 6:

6: EXCEPTION HANDLING

Contents
6.0. Aims and Objectives
6.1. Exception Handling overview
6.2. Exception Class Hierarchy
6.3. Throwable
Throwable Class
6.4. Java Exception Handling Keywords
6.5. Summary
6.6. Model Examination Questions

6.0.
6.0. AIMS AND OBJECTIVES

This unit discusses the nature of exception handling in programming languages. We will
discuss the exception handling types, techniques and basic keywords in exception handling.
After you have studied this unit, you will be able to:

• Know how to use try and catch in your code


• Understand the basics of exception handling
• Differentiate the checked, unchecked and error exceptions

1
6.1. EXCEPTION HANDLING OVERVIEW
OVERVIEW

The ideal time to catch an error is at compile time, before you even try to run the program.
However, not all errors can be detected at compile time. The rest of the problems must be
handled at run time, through some formality that allows the originator of the error to pass
appropriate information to a recipient who will know how to handle the difficulty properly.

C and other earlier languages often had multiple error-handling schemes, and these were
generally established by convention and not as part of the programming language. Typically,
you returned a special value or set a flag, and the recipient was supposed to look at the
value or the flag and determine that something was amiss. However, as the years passed, it
was discovered that programmers who use a library tend to think of themselves as
invincible—as in, “Yes, errors might happen to others, but not in my code.” So, not too
surprisingly, they wouldn’t check for the error conditions (and sometimes the error
conditions were too silly to check for). If you were thorough enough to check for an error
every time you called a method, your code could turn into an unreadable nightmare.
Because programmers could still coax systems out of these languages they were resistant to
admitting the truth: that this approach to handling errors was a major limitation to creating
large, robust, maintainable programs.

The solution is to take the casual nature out of error handling and to enforce formality. The
word “exception” is meant in the sense of “I take exception to that.” At the point where the
problem occurs you might not know what to do with it, but you do know that you can’t just
continue on merrily; you must stop and somebody, somewhere, must figure out what to do.
But you don’t have enough information in the current context to fix the problem. So you
hand the problem out to a higher context where someone is qualified to make the proper
decision (much like a chain of command).
The other rather significant benefit of exceptions is that they clean up error handling code.
Instead of checking for a particular error and dealing with it at multiple places in your
program, you no longer need to check at the point of the method call (since the exception
will guarantee that someone catches it). And, you need to handle the problem in only one
place, the so-called exception handler. This saves you code, and it separates the code that

2
describes what you want to do from the code that is executed when things go awry. In
general, reading, writing, and debugging code becomes much clearer with exceptions than
when using the old way of error handling.

Because exception handling is the only official way that Java reports errors, and it is
enforced by the Java compiler, there are only so many examples that can be written in this
book without learning about exception handling. This chapter introduces you to the code
you need to write to properly handle exceptions, and the way you can generate your
own exceptions if one of your methods gets into trouble.

The causes of exceptions


An exception is a problem that arises during the execution of a program. When an Exception
occurs the normal flow of the program is disrupted and the program/Application
terminates abnormally, which is not recommended, therefore these exceptions are to be
handled. An exception can occur for many different reasons, below given are some scenarios
where exception occurs.
• A user has entered invalid data.
• A file that needs to be opened cannot be found.
• A network connection has been lost in the middle of communications or
• The JVM has run out of memory.

Some of these exceptions are caused by user error, others by programmer error, and others
by physical resources that have failed in some manner. Based on these we have three
categories of Exceptions you need to understand them to know how exception handling
works in Java.

The sun microsystem says there are three types of exceptions:

1. Checked Exception

2. Unchecked Exception

3. Error

3
1.Checked Exceptions: A checked exception is an exception that occurs at the compile time,
these are also called as compile time exceptions. These exceptions cannot simply be ignored
at the time of compilation; the Programmer should take care of handle these exceptions. e.g.
IOException, SQLException etc
• Checked Exceptions All of the other kinds of exceptions
• IOException, ClassNotFoundException, etc.
• These must all be handled in your code .
For example, if you use FileReader class in your program to read data from a file, if the file
specified in its constructor doesn't exist, then a FileNotFoundException occurs, and
compiler prompts the programmer to handle the exception.
import java.io.File;
import java.io.FileReader;
public class FilenotFound_Demo
{
public static void main(String args[])
{
File file=new File("E://file.txt");
FileReader fr = new FileReader(file);
}
}
If you try to compile the above program you will get exceptions as shown below.
C:\>javac FilenotFound_Dem o.java
FilenotFound_Dem o.java:8: error: unreported exception FileNotFoundException; must be
caught or declared to be thrown
FileReader fr = new FileReader(file);
1 error
Note: Since the methods read and close of FileReader class throws IOException, you can
observe
that compiler notifies to handle IOException, along with FileNotFoundException.

4
2.Unchecked exceptions: An Unchecked exception is an exception that occurs at the time
of execution, these are also called as Runtime Exceptions, these include programming bugs,
such as logic errors or improper use of an API. Runtime exceptions are ignored at the time of
compilation.
For example, if you have declared an array of size 5 in your program, and trying to call the
6th element of the array then an ArrayIndexOutOfBoundsExceptionexception occurs.
public class Unchecked_Demo
{
public static void main(String args[])
{
int num []={1,2,3,4};
System .out.println(num [5]);
}
}
If you compile and execute the above program you will get exception as shown below.
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
at Exceptions.Unchecked_Dem o.main(Unchecked_Dem o.java:8)

3.Errors: These are not exceptions at all, but problems that arise beyond the control of the
user or the programmer. Errors are typically ignored in your code because you can rarely do
anything about an error. For example, if a stack overflow occurs, an error will arise. They
are also ignored at the time of compilation.

Check your progress-1


1. Explain what exceptions are in programming languages?
_________________________________________________________________________________________________
_________________________________________________________________________________________________

5
6.2. EXCEPTION CLASS HIERARCHY
HIERARCHY

All exception classes are subtypes of the java.lang.Exception class. The exception class is a
subclass of the Throwable class. Other than the exception class there is another subclass
called Error which is derived from the Throwable class.

Errors are abnormal conditions that happen in case of severe failures, these are not
handled by the Java programs. Errors are generated to indicate errors generated by the
runtime environment. Example: JVM is out of memory. Normally, programs cannot
recover from errors.

The Exception class has two main subclasses: IOException class and RuntimeException
Class.

Exception Methods
Following is the list of important methods available in the Throwable class.

Sr.No. Method & Description

1 public String getMessage()


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

6
2 public Throwable getCause()
Returns the cause of the exception as represented by a Throwable object.

3 public String toString()


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

4 public void printStackTrace()


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

5 public StackTraceElement [] getStackTrace()


Returns an array containing each element on the stack trace. The element at
index 0 represents the top of the call stack, and the last element in the array
represents the method at the bottom of the call stack.

6 public Throwable fillInStackTrace()


Fills the stack trace of this Throwable object with the current stack trace,
adding to any previous information in the stack trace.

Catching Exceptions

A method catches an exception using a combination of the try and catch keywords. A
try/catch block is placed around the code that might generate an exception. Code within a
try/catch block is referred to as protected code, and the syntax for using try/catch looks
like the following: Syntax

try {

// Protected code

} catch (ExceptionName e1) {

// Catch block

7
The code which is prone to exceptions is placed in the try block. When an exception
occurs, that exception occurred is handled by catch block associated with it. Every try
block should be immediately followed either by a catch block or finally block.

A catch statement involves declaring the type of exception you are trying to catch. If an
exception occurs in protected code, the catch block (or blocks) that follows the try is
checked. If the type of exception that occurred is listed in a catch block, the exception is
passed to the catch block much as an argument is passed into a method parameter.

Example
The following is an array declared with 2 elements. Then the code tries to access the
3rd element of the array which throws an exception.

import java.io.*;

public class ExcepTest {

public static void main(String args[]) {

try {

int a[] = new int[2];

System.out.println("Access element three :" + a[3]);

} catch (ArrayIndexOutOfBoundsException e) {

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

System.out.println("Out of the block");

This will produce the following result:

8
Output

Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3

Out of the block

Check your progress-2


1. Explain the try-catch exception?
_________________________________________________________________________________________________
_________________________________________________________________________________________________

6.3. THE THROWABLE


THROWABLE CLASS

Java exceptions are objects. Since they're objects, different types of exceptions can be
subclasses of one another, just as with other objects. For Instance, FileNotFoundException is
an extension of IOException. If we catch IOException, then by implication, we also catch
FileNotFoundException.

From the base upwards, Java exception classes are organized into a hierarchy. There is a
basic exception class called Exception as you might expect. But in fact, the base of the
hierarchy starts not with Exception but with a class called Throwable, which is then
subclassed into Exception and Error. Part of the hierarchy is illustrated in the following
Figure.

The rationale behind the hierarchy is as follows:

• Exception subclasses represent errors that a program can reasonably recover from.
Except for RuntimeException and its subclasses (see below), they generally represent
errors that a program will expect to occur in the normal course of duty: for example,
network connection errors and filing system errors.

• Error subclasses represent "serious" errors that a program generally shouldn't expect to
catch and recover from. These include conditions such as an expected class file being
missing, or an OutOfMemoryError.

9
• RuntimeException is a further subclass of Exception. RuntimeException and its
subclasses are slightly different: they represent exceptions that a program shouldn't
generally expect to occur, but could potentially recover from. They represent what are
likely to be programming errors rather than errors due to invalid user input or a badly
configured environment.

6.4. JAVA EXCEPTION HANDLING


HANDLING KEYWORDS

There are 5 keywords used in java exception handling.

1. try

2. catch

3. finally

4. throw

5. throws

Catching Exceptions:

A method catches an exception using a combination of the try and catch keywords. A
try/catch block is placed around the code that might generate an exception. Code within a
try/catch block is referred to as protected code, and the syntax for using try/catch looks
like the following:
try
{
//Protected code
}
catch(ExceptionName e1)
{
//Catch block

1. The code which is prone to exceptions is placed in the try block, when an exception

10
occurs; that exception occurred is handled by catch block associated with it. Every try
block should be immediately followed either by a class block or finally block.
2. A catch statement involves declaring the type of exception you are trying to catch. If an
exception occurs in protected code, the catch block or blocks that follows the try is
checked. If the type of exception that occurred is listed in a catch block, the exception is
passed to the catch block much as an argument is passed into a method parameter.

Example:
The following is an array is declared with 2 elements. Then the code tries to access the 3rd
element of the array which throws an exception.
Import java.io.*;
public class ExcepTest{
public static void main(String args[]){
try{
int a[] = new int[2];
System .out.println("Access element three :" + a[3]);
}
catch(ArrayIndexOutOfBoundsException e){
System .out.println("Exception thrown :" + e);
}
System .out.println("Out of the block");
}
}
This would produce the following result:
Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3
Out of the block

Multiple catch Blocks: A try block can be followed by multiple catch blocks. The syntax for

11
multiple catch blocks looks like the following:
try
{
//Protected code
}
catch(ExceptionType1 e1)
{
//Catch block
}
catch(ExceptionType2 e2)
{
//Catch block
}
catch(ExceptionType3 e3)
{
//Catch block
}

The previous statements demonstrate three catch blocks, but you can have any number of
them after a single try. If an exception occurs in the protected code, the exception is thrown
to the first catch block in the list. If the data type of the exception thrown matches
ExceptionType1, it gets caught there. If not, the exception passes down to the second catch
statement. This continues until the exception either is caught or falls through all catches, in
which case the current method stops execution and the exception is thrown down to the
previous method on the call stack.

The throws/throw Keywords:


If a method does not handle a checked exception, the method must declare it using the
throws keyword. The throws keyword appears at the end of a method's signature. You can

12
throw an exception, either a newly instantiated one or an exception that you just caught, by
using the throw keyword.

Try to understand the difference between throws and throw keywords, throws is used to
postpone the handling of a checked exception and throw is used to invoke an exception
explicitly. The following method declares that it throws a RemoteException:
import java.io.* ;
public class className {
public void deposit(double amount) throws RemoteException
{
// Method implementation
throw new RemoteException();
}
//Remainder of class definition
}

A method can declare that it throws more than one exception, in which case the exceptions
are declared in a list separated by commas. For example, the following method declares
that it throws a RemoteException and an InsufficientFundsException:
import java.io.* ;
public class className
{
public void withdraw(double am unt) throws
RemoteException,InsufficientFundsException
{
// Method implem entation
}
//Remainder of class definition
}
The finally block

13
The finally block follows a try block or a catch block. A finally block of code always
executes, irrespective of occurrence of an Exception. Using a finally block allows you to run
any cleanup-type statements that you want to execute, no matter what happens in the
protected code. A finally block appears at the end of the catch blocks and has the following
syntax:
try
{
//Protected code
}catch(ExceptionType1 e1)
{
//Catch block
}catch(ExceptionType2 e2)
{
//Catch block
}catch(ExceptionType3 e3)
{
//Catch block
}
Finally
{
//The finally block always executes.
}

Example:
public class ExcepTest{
public static void m ain(String args[])
{
int a[] = new int[2];
try
{
System .out.println("Access element three :" + a[3]);
}
Catch (ArrayIndexOutOfBoundsException e)

14
{
System .out.println("Exception thrown :" + e);
}
Finally
{
a[0] = 6;
System .out.println("First elem ent value: " +a[0]);
System .out.println("The finally statem ent is executed");
}
}
}

This would produce the following result:

Exception thrown: java.lang.ArrayIndexOutOfBoundsException: 3

First element value: 6

The finally statement is executed

Note the following:

1. A catch clause cannot exist without a try statement.

2. It is not compulsory to have finally clauses whenever a try/catch block is present.

3. The try block cannot be present without either catch clause or finally clause.

4. Any code cannot be present in between the try, catch, finally blocks.

User-defined Exceptions:

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 write a checked exception that is automatically enforced by the

15
Handle or Declare Rule, you need to extend the Exception class.

1. If you want to write a runtime exception, you need to extend the RuntimeException
class.

We can define our own Exception class as below:

class MyException extends Exception

You just need to extend the predefined Exception class to create your own Exception. These
are considered to be checked exceptions. The following InsufficientFundsException class is
a user defined exception that extends the Exception class, making it a checked exception.
An exception class is like any other class, containing useful fields and methods.

Example:
// File Nam e InsufficientFundsException.java
import java.io.* ;
public class InsufficientFundsException extends Exception
{
private double amount;
public InsufficientFundsException(double amount)
{
this.amount = amount;
}
public double getAmount()
{
return amount;
}
}

To demonstrate using our user-defined exception, the following CheckingAccount class


contains a withdraw method that throws an InsufficientFundsException.

16
// File Nam e CheckingAccount.java
import java.io.* ;
public class CheckingAccount
{
private double balance;
private int number;
public CheckingAccount(int number)
{
this.number = number;
}
public void deposit (double amount)
{
balance += amount;
}
public void withdraws (double am ount) throws InsufficientFundsException
{
if (am ount <= balance)
{
balance -= am ount;
}
else
{
double needs = am ount - balance;
throw new InsufficientFundsException(needs);
}
}
public double getBalance()
{
return balance;
}
public int getNumber()
{
return number;
}
}

The following BankDemo program demonstrates invoking the deposit and withdraw
methods of CheckingAccount.

17
// File Name BankDemo.java
public class BankDem o
{
public static void main(String [] args)
{
CheckingAccount c = new CheckingAccount(101);
System.out.println("Depositing $ 500...");
c.deposit(500.00);
try
{
System .out.println("\nWithdrawing $ 100...");
c.withdraw(100.00);
System .out.println("\nWithdrawing $ 600...");
c.withdraw(600.00);
}catch(InsufficientFundsException e)
{
System .out.println("Sorry, but you are short $ " + e.getAmount());
e.printStackTrace();
}
}
}
Compile all the above three files and run BankDemo, this would produce the following
result:
Depositing $ 500...
Withdrawing $ 100...
Withdrawing $ 600...
Sorry, but you are short $ 200.0
InsufficientFundsException
at CheckingAccount.withdraw(CheckingAccount.java:25)
at BankDem o.main(BankDemo.java:13)

18
Check your progress-3
1. List at least 4 exception handling techniques?
_________________________________________________________________________________________________
_________________________________________________________________________________________________

6.5. SUMMARY

An exception is an unwanted or unexpected event, which occurs during the execution of a


program i.e. at run time, that disrupts the normal flow of the program’s instructions.
Error: An Error indicates serious problem that a reasonable application should not try to
catch. Exception: Exception indicates conditions that a reasonable application might try to
catch.
All exception and errors types are sub classes of class Throwable, which is base class of
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 are used by the Java run-time system to indicate errors having to do
with the run-time environment itself(JRE). StackOverflowError is an example of such an
error.
An exception (or exceptional event) is a problem that arises during the execution of a
program. When an Exception occurs the normal flow of the program is disrupted and the
program/Application terminates abnormally, which is not recommended, therefore, these
exceptions are to be handled.

An exception can occur for many different reasons. Following are some scenarios where
an exception occurs.

• A user has entered an invalid data.

• A file that needs to be opened cannot be found.

• A network connection has been lost in the middle of communications or the JVM
has run out of memory.

19
6.6. MODEL EXAMINATION QUESTIONS.
QUESTIONS.

I: True/False questions
1. A checked exception is an exception that occurs at the compile time.
2. When an Exception occurs the normal flow of the program is disrupted and the
program terminates abnormally.
3. A finally block of code always executes, irrespective of occurrence of an
Exception.
4. Errors are not exceptions at all, but problems that arise beyond the control of
the user or the programmer.
II: Short Answer Questions

1. Explain the three types of errors with examples?


2. Write a syntax of exception handling?

20

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