0% found this document useful (0 votes)
9 views22 pages

Java Exception Handling Basics

The document provides an overview of exception handling in Java, detailing types of errors (compile-time and run-time), the exception hierarchy, and mechanisms for handling exceptions using try, catch, and finally blocks. It explains how to throw and catch exceptions, as well as the use of assertions for defensive programming. Additionally, it covers stack trace elements and their utility in debugging exceptions during program execution.

Uploaded by

zohosaravanan
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)
9 views22 pages

Java Exception Handling Basics

The document provides an overview of exception handling in Java, detailing types of errors (compile-time and run-time), the exception hierarchy, and mechanisms for handling exceptions using try, catch, and finally blocks. It explains how to throw and catch exceptions, as well as the use of assertions for defensive programming. Additionally, it covers stack trace elements and their utility in debugging exceptions during program execution.

Uploaded by

zohosaravanan
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

Exception Handling 11.

11 Exception Handling

11.1 Introduction to Exception Handling


Error
Errors are mistake that makes a program go wrong.

If error occurred, program may produce incorrect output (or) may terminate the
execution of the program. So the error should be detected and managed properly. Then
the program will work properly.

 Notify the user of an error


 Save all work
 Allow users to gracefully exit the program.

Types of errors

Errors

Compile Run time


Time Error Errors

Figure 11.1 Types of error

i) Compile time errors


This type of error is occurred during the time of compilation. If a program has the
compilation error then .class file is not been created.
Example:

Class sample
{
public static void main(string args{})
{
[Link](“welcome to java)
int a=5, b=10;
c=a+b;
[Link](“the value of c is”+c);
}
Here errors will give priority like
11.2 Java Programming Paradigms

 Unclosed string literal-> for line number 5. That is double quotes is not been
closed.
 Next show for expected ;( semicolon) -> for line number 5.
 After clear this errors it will show the other errors. Like
 Cannot find the symbol string -> for line number 3. Here String S should be
capital.
 Cannot find the symbol c -> for line number 7 and 8. Were integer c is not
declared as variable.
 The error message will show the line number and we go the particular line and we
can clear the error.
 Sometime, it will show single error when we correct the error it would be shown
for multiple lines of errors.

ii) Run Time Error


After successful compilation of the program (i.e. .class file has been
created).while running a program it will produce an error.
The most common runt time errors are
 Dividing an integer by zero.
 Array index out of range.

Dealing with errors


 User input errors: Example that a user asks to connect to a URL that is
syntactically wrong. Your code should check the syntax, but suppose it does not.
Then the network layer will complain.
 Device errors: Hardware do not always do what you want it to. The printer may
be turned off. A web page may be temporarily unavailable. Devices will often fail
in the middle of a task. For example, a printer may run out of paper during
printing.
 Physical limitations: Disks can fill up; you can run out of available memory.
 Code errors: A method may not perform correctly. For example, it could deliver
wrong answers or use other methods incorrectly. Computing an invalid array
index, trying to find nonexistent entry in a hash table, and trying to pop an empty
stack are all examples of a code error.

11.2 Exceptions Hierarchy


In the Java programming language, an exception object is always an instance of a
class derived from Throwable.
All exceptions descend from Throwable, but the hierarchy immediately splits into
two branches: Error and Exception.
Exceptions that inherit from RuntimeException include such problems as
Exception Handling 11.3

• A bad cast
• An out-of-bounds array access
• A null pointer access

Exceptions that do not inherit from RuntimeException include

• Trying to read past the end of a file


• Trying to open a malformed URL
• Trying to find a Class object for a string that does not denote an existing class.

Figure 11.2 shows the simplified diagram of the exception hierarchy in Java.

Object

Throwable

Error Exception

IOException Runtime
Exception

IOException ArrayStoreExceptio
n
Figure 11.2 Exception hierarchy in java

11.3 Exception Handling

 An exception is a condition that occurred at run time execution of a program.


 In java exception is an object. If the exception is not caught then the interpreter
will encounter an error message and terminate the program.
11.4 Java Programming Paradigms

 If we want to execute the program, then we should catch the exception object
thrown by the error condition and display message for taking correct action is
called exception handling.

Keyword used for handling exception are try, catch, throw, throws, finally.

Exception handling works like

In the program code, where the exception is occurred should have try block. And
should be thrown. Then this exception must be caught using catch and this is placed
immediately after the try block. To manually throw an exception, use the keyword throw.
Any exception that is thrown out of a method must be specified as such by a throws
clause.

An exception is not caught by any of the previous catch statement. Finally block
can be used to handle any exception generated within a try block. It is placed after the last
catch block.
try block
statement that causes an
exception

throws exception
object

catch block

handling exception

Figure 11.3 Exception Handling Mechanism


Exception Handling 11.5

The general format of exception handling block.

try
{
//code thatg to be monitored.
}
catch(Exception_type obj)
{
//exception handler for exception_type1
}
catch(Exception_type2 obj)
{
//exception handler for exception_type2
}
finally
{
//block of code to be executed before try block ends
}

Here, exception type is the type of exception that has occurred and obj is the
exception object.

11.4 try-catch-finally

try block

The general form of try block is

try
{
---------
statement;
---------
}

Try block is defined by ‘try’ keyword. Try block is used to test the program
statement for run time error (Exception). Try block can have one or more statements that
that could generate an exception. If any statement generates an exception then the
remaining statements in the block are skipped and execution jumps to the catch block that
is placed next to the try block.
11.6 Java Programming Paradigms

catch Block

-----
catch(ExceptionCalss obj1)
{
------
// Error handling statements1
------
}
catch(ExceptionCalss obj2)
{
------
// Error handling statements2
------
}
-
-
-
catch(ExceptionCalss objn)
{
------
// Error handling statementsn
------
}
Catch block is defined by ‘catch’ keyword. The catch block can also have one or
more statements that are needed to process the exceptions that are occurred in try block.
Every try statement should be followed by at least one catch statement, otherwise
compilation error will occur.

Note that the catch statement works like a method definition. The catch statement
is passed a single parameter, which is reference to the exception object thrown (by the try
block). If the catch parameter matches with the type of exception object, then the
exception is caught and statements in the catch block will be executed. Otherwise, the
exception is not caught and the default exception handler will cause the execution to
terminate.
Example Program:
class trycatch
{
public static void main(String args[])
{
int d,a;
try
Exception Handling 11.7

{
d=0;
a=10/d;
[Link]("Successful Statement");
}
catch(ArithmeticException e)
{
[Link]("Division by Zero");
}
[Link]("After catch statement");
}
}
Program 11.1 Example for try catch
Output:
I:\java\Exception>javac [Link]

I:\java\Exception>java trycatch
Division by Zero
After catch statement

Multiple Catch Statement


class multicatch
{
public static void main(String args[])
{
int a[]={5,10};
int b=5;
try
{
int x=a[2]/b-a[1];
}
catch(ArithmeticException e)
{
[Link]("Divide by Zero");
}
catch(ArrayIndexOutOfBoundsException e)
{
[Link]("Array index error");
}
catch(ArrayStoreException e)
{
[Link]("Wrong Data Type");
11.8 Java Programming Paradigms

}
int y=a[1]/a[0];
[Link]("y="+y);
}
}
Program 11.2 Example for multiplecatch
Output
I:\java\Exception>javac [Link]

I:\java\Exception>java multicatch
Array index error
y=2

Finally statement
This block is used to handle an exception that is not caught by any of the previous
catch statements; finally block can be used to handle any exception generated within a try
block. It can be added immediately after the try block or after the last catch block as
shown as follows.
When a finally block is defined, this is guarantee to execute, regardless of
whether or not in exception is thrown.

try try
{ {
---- ----
---- ----
} }
finally catch1(----)
{ {
---- ----
---- ----
} }
catch2(----)
{
----
----
}
finally
{
----
----
}
Exception Handling 11.9

class trycatchfinally
{
public static void main(String args[])
{
int a[]={5,10};
int b=5;
try
{
int x=a[2]/b-a[1];
}
catch(ArithmeticException e)
{
[Link]("Divide by Zero");
}
catch(ArrayIndexOutOfBoundsException e)
{
[Link]("Array index error");
}
catch(ArrayStoreException e)
{
[Link]("Wrong Data Type");
}
finally
{
int y=a[1]/a[0];
[Link]("y="+y);
}
}
}

Program 11.3 Example for try-catch-finally

Output

I:\java\Exception>javac [Link]

I:\java\Exception>java trycatchfinally
Array index error
y=2
11.10 Java Programming Paradigms

throw
The throw keyword is used to explicitly throw an exception.
throw ThrowableInstance;
class throwclass
{
static void method()
{
try
{
throw new ArrayIndexOutOfBoundsException("Sample");
}
catch(ArrayIndexOutOfBoundsException e)
{
[Link]("Caught inside method.");
throw e;
}
}
public static void main(String args[])
{
try
{
method();
}
catch(ArrayIndexOutOfBoundsException e)
{
[Link]("Recaught:"+e);
}
}
}
Program 11.4 Example for throw
Output:
E:\javaprograms>javac [Link]
E:\javaprograms>java throwclass
Caught inside method.
Recaught:[Link]: Sample

throws
General form of throws statement:
type method_name(parameters) throws exception1, exception2,…….
{
Statements;
}
Exception Handling 11.11

Example:
import [Link];
class throwsclass
{
static void method() throws IOException
{
[Link]("Method");
throw new IOException("throws ioexception");
}
public static void main(String args[])
{
try
{
method();
}
catch(IOException e)
{
[Link]("Caught" +e);
}
}}
Program 11.5 Example for throws

Output
I:\java\Exception>javac [Link]
I:\java\Exception>java throwsclass
Method
[Link]: throws ioexception

11.5 Stack Trace Elements

A stack trace is a listing of all pending method calls at a particular point in the
execution of a program. You have almost certainly seen stack trace listings—they are
displayed whenever a Java program terminates with an uncaught exception.

Before Java SE 1.4, you could access the text description of a stack trace by
calling the printStackTrace() method of the Throwable class. Now you can call the
getStackTrace ()method to get an array of StackTraceElement objects that you can
analyze in your program. For example:

Throwable t = new Throwable();


11.12 Java Programming Paradigms

StackTraceElement[] frames = [Link]();


for (StackTraceElement frame : frames)
analyze frame
The StackTraceElement class has methods to obtain the file name and line
number, as well as the class and method name, of the executing line of code. The toString
method yields a formatted string containing all of this information.

import [Link].*;
public class StackTraceTest
{
/**
* Computes the factorial of a number
* @param n a nonnegative integer
* @return n! = 1 * 2 * . . . * n
*/
public static int factorial(int n)
{
[Link]("factorial(" + n + "):");
Throwable t = new Throwable();
StackTraceElement[] frames = [Link]();
for (StackTraceElement f : frames)
[Link](f);
int r;
if (n <= 1) r = 1;
else r = n * factorial(n - 1);
[Link]("return " + r);
return r;
}
public static void main(String[] args)
{
Scanner in = new Scanner([Link]);
[Link]("Enter n: ");
int n = [Link]();
factorial(n);
}
}

Program 11.6 StackTrace of a recursive factorial function.


Output:
I:\java\Exception>javac [Link]

I:\java\Exception>java StackTraceTest
Exception Handling 11.13

Enter n: 3
factorial(3):
[Link]([Link])
[Link]([Link])
factorial(2):
[Link]([Link])
[Link]([Link])
[Link]([Link])
factorial(1):
[Link]([Link])
[Link]([Link])
[Link]([Link])
[Link]([Link])
return 1
return 2
return 6

Methods of [Link]
Method Description
boolean Returns true if the specified object is another StackTraceElement
equals(Object obj) instance representing the same execution point as this instance.
String Returns the fully qualified name of the class containing the
getClassName() execution point represented by this stack trace element.
String Returns the name of the source file containing the execution point
getFileName() represented by this stack trace element.
int Returns the line number of the source line containing the execution
getLineNumber() point represented by this stack trace element.
String Returns the name of the method containing the execution point
getMethodName() represented by this stack trace element.
int hashCode() Returns a hash code value for this stack trace element.
boolean Returns true if the method containing the execution point
isNativeMethod() represented by this stack trace element is a native method.
String Returns a string rep
toString() resentation of this stack trace element.
Table 11.1 Methods of [Link]
11.14 Java Programming Paradigms

11.6 Using Assertions

Assertions are a commonly used idiom for defensive programming. Suppose you
are convinced that a particular property is fulfilled, and you rely on that property in your
code. For example, you may be computing

double y = [Link](x);

You are certain that x is not negative. Perhaps it is the result of another
computation that can’t have a negative result, or it is a parameter of a method that
requires its callers to supply only positive inputs. Still, you want to double-check rather
than having confusing “not a number” floating-point values creep into your computation.
You could, of course, throw an exception:

if (x < 0) throw new IllegalArgumentException("x < 0");

But this code stays in the program, even after testing is complete. If you have lots
of checks of this kind, the program runs quite a bit slower than it should.

The assertion mechanism allows you to put in checks during testing and to have
them automatically removed in the production code.

As of Java SE 1.4, the Java language has a keyword assert. There are two forms:

assert condition;
and
assert condition : expression;

Both statements evaluate the condition and throw an AssertionError if it is false.


In the second statement, the expression is passed to the constructor of the AssertionError
object and turned into a message string.

To assert that x is nonnegative, you can simply use the statement


assert x >= 0;
Or you can pass the actual value of x into the AssertionError object, so that it gets
displayed later.
assert x >= 0 : x;

Assertion Enabling and Disabling


By default, assertions are disabled. You enable them by running the program with
the -enable assertions or -ea option:
java -enableassertions MyApp
Exception Handling 11.15

Enabling or disabling assertions is a function of the class loader. When assertions


are disabled, the class loader strips out the assertion code

you can even turn on assertions in specific classes or in entire packages. For example:

java -ea:MyClass -ea:[Link]... MyApp

This command turns on assertions for the class My Class and all classes in the
com .mycompany .mylib package and its sub packages.

You can also disable assertions in certain classes and packages with the –
disableassertions or -da option:

java -ea:... -da:MyClass MyApp

Some classes are not loaded by a class loader but directly by the virtual machine.
You can use these switches to selectively enable or disable assertions in those classes.

However, the -ea and -da switches that enable or disable all assertions do not
apply to the “system classes” without class loaders. Use the -enablesystemassertions/-esa
switch to enable assertions in system classes.

Using Assertions for Parameter Checking

The Java language gives you three mechanisms to deal with system failures:
• Throwing an exception
• Logging
• Using assertions
When should you choose assertions? Keep these points in mind:
• Assertion failures are intended to be fatal, unrecoverable errors.
• Assertion checks are turned on only during development and testing.
Checking of method parameters.

@param a the array to be sorted.


@param fromIndex the index of the first element
(inclusive) to be sorted.
@param toIndex the index of the last element
(exclusive) to be sorted.
@throws IllegalArgumentException if fromIndex >
toIndex
11.16 Java Programming Paradigms

@throws ArrayIndexOutOfBoundsException if fromIndex


< 0 or toIndex > [Link]
*/
static void sort(int[] a, int fromIndex, int toIndex)

However, suppose the method contract had been slightly different:

@param a the array to be sorted. (Must not be null)

Now the callers of the method have been put on notice that it is illegal to call the method
with a null array. Then the method may start with the assertion

assert a != null;

Computer scientists call this kind of contract a precondition. The original method had no
preconditions on its parameters

Using Assertions for Documenting Assumptions

Many programmers use comments to document their underlying assumptions.

if (i % 3 == 0)
...
else if (i % 3 == 1)
...
else // (i % 3 == 2)
...
if (i % 3 == 0)
...
else if (i % 3 == 1)
...
else
{
assert i % 3 == 2;
...
}
Of course, it would make even more sense to think through the issue a bit more
thoroughly. What are the possible values of i % 3? If i is positive, the remainders must be
0, 1, or 2. If i is negative, then the remainders can be −1 or −2. Thus, the real assumption
is that i is not negative. A better assertion would be
assert i >= 0;
before the if statement.
Exception Handling 11.17

11.7 Logging

Every Java programmer is familiar with the process of inserting calls to System
.[Link] into troublesome code to gain insight into program behavior. Of course, once
you have figured out the cause of trouble, you remove the print statements, only to put
them back in when the next problem surfaces. The logging API is designed to overcome
this problem.

Here are the principal advantages of the API:

 It is easy to suppress all log records or just those below a certain level, and just as
easy to turn them back on.
 Suppressed logs are very cheap, so that there is only a minimal penalty for leaving
the logging code in your application.
 Log records can be directed to different handlers, for display in the console, for
storage in a file, and so on.
 Both loggers and handlers can filter records. Filters discard boring log entries,
using any criteria supplied by the filter implementor.
 Log records can be formatted in different ways, for example, in plain text or
XML.
 Applications can use multiple loggers, with hierarchical names such as
[Link], similar to package names.
 By default, the logging configuration is controlled by a configuration file.
Applications can replace this mechanism if desired.

11.7.1 Basic Logging


The logging system manages a default logger [Link] that you can use
instead of [Link]. Use the info method to log an information message:

[Link]("File->Open menu item selected");


By default, the record is printed like this:
May 10, 2004 10:12:15 PM LoggingImageViewer fileOpen
INFO: File->Open menu item selected
Note that the time and the names of calling class and methods are automatically
include.

11.7.2 Advanced Logging

In a professional application, you wouldn’t want to log all records to a single


global logger. Instead, you can define your own loggers. When you request a logger with
a given name for the first time, it is created.
11.18 Java Programming Paradigms

Logger myLogger = [Link]("[Link]");


Subsequent calls to the same name yield the same logger object.

Similar to package names, logger names are hierarchical. In fact, they are more
hierarchical than packages. There is no semantic relationship between a package and its
parent, but logger parents and children share certain properties. For example, if you set
the log level on the logger "[Link]", then the child loggers inherit that level.

There are seven logging levels:


• SEVERE
• WARNING
• INFO
• CONFIG
• FINE
• FINER
• FINEST

By default, the top three levels are actually logged. You can set a different level, for
example,

logger. setLevel ([Link]);

Now all levels of FINE and higher are logged.

You can also use [Link] to turn on logging for all levels or Level. There are logging
methods for all levels, such as

[Link](message);
[Link](message);

and so on. Alternatively, you can use the log method and supply the level, such as

logger .log (Level .FINE, message);

The default log record shows the name of the class and method that contain the logging
call, as inferred from the call stack. However, if the virtual machine optimizes execution,
accurate call information may not be available. You can use the logp method to give
theprecise location of the calling class and method. The method signature is

void logp(Level l, String className, String methodName, String message)

There are convenience methods for tracing execution flow:


Exception Handling 11.19

void entering(String className, String methodName)


void entering(String className, String methodName, Object param)
void entering(String className, String methodName, Object[] params)
void exiting(String className, String methodName)
void exiting(String className, String methodName, Object result)
For example:
int read(String file, String pattern)
{
[Link]("[Link]", "read",
new Object[] { file, pattern });
...
[Link]("[Link]", "read", count);
return count;
}

These calls generate log records of level FINER that start with the strings ENTRY and
RETURN.

A common use for logging is to log unexpected exceptions. Two convenience methods
include a description of the exception in the log record.

void throwing(String className, String methodName, Throwable t)


void log(Level l, String message, Throwable t)
Typical uses are
if (. . .)
{
IOException exception = new IOException(". . .");
[Link]("[Link]", "read", exception);
throw exception;
}
and
try
{
...
}
catch (IOException e)
{
[Link]("[Link]").log([Link],
"Reading image", e);
}
The throwing call logs a record with level FINER and a message that starts with
THROW.
11.20 Java Programming Paradigms

11.7.3 Changing the Log Manager Configuration

You can change various properties of the logging system by editing a


configuration file.
The default configuration file is located at
jre/lib/[Link]
To use another file, set the [Link] property to the file location
by starting your application with
java -[Link]=configFile MainClass
to change the default logging level, edit the configuration file and modify the line
.level=INFO
You can specify the logging levels for your own loggers by adding lines such as
[Link]=FINE
That is, append the .level suffix to the logger name. As you see later in this section, the
loggers don’t actually send the messages to the console— that is the job of the handlers.
Handlers also have levels. To see FINE messages on the console, you also need to set
java .util .logging .Console Handler .level =FINE

11.7.4 Handlers
Loggers send records to a ConsoleHandler that prints them to the [Link]
stream. Specifically, the logger sends the record to the parent handler, and the ultimate
ancestor (with name "") has a ConsoleHandler.
Like loggers, handlers have a logging level. For a record to be logged, its logging
level must be above the threshold of both the logger and the handler. The log manager
configuration file sets the logging level of the default console handler as java .util
.logging .Console Handle [Link] =INFO
To log records with level FINE, change both the default logger level and the
handler level in the configuration. Alternatively, you can bypass the configuration file
altogether and install your own handler.
Logger logger = [Link]("[Link]");
[Link]([Link]);
[Link](false);
Handler handler = new ConsoleHandler();
[Link]([Link]);
[Link](handler);
Exception Handling 11.21

By default, a logger sends records both to its own handlers and the handlers of the
parent. Our logger is a child of the primordial logger (with name "") that sends all records
with level INFO or higher to the console. But we don’t want to see those records twice.
For that reason, we set the useParentHandlers property to false.

To send log records elsewhere, add another handler. The logging API provides
two useful handlers for this purpose, a FileHandler and a SocketHandler. The
SocketHandler sends records to a specified host and port. Of greater interest is the
FileHandler that collects records in a file.

You can simply send records to a default file handler, like this:

FileHandler handler = new FileHandler();


[Link](handler);

The records are sent to a file [Link] in the user’s home directory, where n is a
number to make the file unique. If a user’s system has no concept of the user’s home
directory (for example, in Windows 95/98/Me), then the file is stored in a default location
such as C:Windows. By default, the records are formatted in XML. A typical log record
has the form

<record>
<date>2002-02-04T07:45:15</date>
<millis>1012837515710</millis>
<sequence>1</sequence>
<logger>[Link]</logger>
<level>INFO</level>
<class>[Link]</class>
<method>read</method>
<thread>10</thread>
<message>Reading file [Link]</message>
</record>

11.7.5 Filters
By default, records are filtered according to their logging levels. Each logger and
handler can have an optional filter to perform added filtering. You define a filter by
implementing the Filter interface and defining the method
boolean isLoggable(LogRecord record)
Analyze the log record, using any criteria that you desire, and return true for those
records that should be included in the log. For example, a particular filter may only be
interested in the messages generated by the entering and exiting methods. The filter
11.22 Java Programming Paradigms

should then call [Link]() and check whether it starts with ENTRY or
RETURN.
To install a filter into a logger or handler, simply call the setFilter method. Note
that you can have at most one filter at a time.

11.7.6 Formatters

The ConsoleHandler and FileHandler classes emit the log records in text and
XML formats. However, you can define your own formats as well. You need to extend
the Formatter class and override the method

String format(LogRecord record)

Format the information in the record in any way you like and return the resulting
string. In your format method, you may want to call the method

String formatMessage(LogRecord record)

That method formats the message part of the record, substituting parameters and
applying localization. Many file formats (such as XML) require a head and tail part that
surrounds the formatted records. In that case, override the methods

String getHead(Handler h)
String getTail(Handler h)

Finally, call the setFormatter method to install the formatter into the handler.

Review Questions
Part-A
1) What is exception handling?
2) What is runtime error? Give example.
3) What is compile time error.
4) Give the general syntax for try, catch and finally.

Part-B
1) Explain exception handling in detail.
2) Give examples for try, catch and throw.
3) Explain assertions in detail
4) Explain logging in detail.

You might also like