Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 5

Traditional error handling methods such as errno are problematic in large-scale

applications because they don't guarantee that runtime errors are actually caught
and handled

Runtime errors often occur when a low-level piece of code is executing. These low-
level functions cannot—and should not—try to handle the exception by themselves.
Instead, they should notify their caller of the error and let it decide how to handle it.
Chances are that somewhere up in the call chain, information about the exception
might be lost, thereby causing the application to mishandle it or ignore it altogether.

Use exceptions to pass information about anomalous runtime conditions and to


transfer control to an appropriate handler.

Exceptions Handling Constructs


The keywords try, catch, and throw are used in exception handling. try defines a
block of guarded code i.e., a sequence of one or more statements that might throw
an exception. catch defines a catch-block, or a handler, for a particular exception or
a set of exceptions. A throw statement interrupts the current execution flow and
propagates an exception to a matching handler.

Step 1: Defining Exceptions

An exception can be a datatype such as int or a class object. The use of classes
allows you to define hierarchies of exceptions by means of derivation. Suppose you
have a function called alloc() that allocates a memory block of a requested size from
a private memory pool. alloc() detects anomalous runtime conditions such as an
invalid block size and throws an appropriate exception.

Step 2: Handling Exceptions


Upon entering a handler, an exception is considered handled. The handler looks as
follows:

As a rule, pass exceptions by reference, not by value. Inside the catch block, you can
try to fix the problem or log the error and exit:

Step 3: Putting it to Work


Only exceptions that occur inside a try block can be caught. In the following
program, the alloc() call isn't enclosed in a try-block. Consequently, the exception it
throws will cause the program to terminate abnormally

When an exception occurs, the normal flow of execution is interrupted and the
exception handling mechanism starts searching for a matching handler in the current
scope. If it can't find one, it pops the current function from the stack and the search
resumes in its caller. This process is called stack unwinding and it continues until a
matching handler is found or, if a matching handler doesn't exist, the program
terminates

Step 4: Handlers' Ordering


For the sake of brevity, a single exception class is used here. However, in real world
application it's customary to define multiple catch blocks that handle various types of
exceptions. When using multiple handlers, always place the most derived handler
before a base class handler.

Exception handling is a programming language construct or computer hardware


mechanism designed to handle the occurrence of exceptions - special conditions that
change the normal flow of execution.

xceptions are typically used to signal that something went wrong (e.g. a division by zero
occurred or a required file was not found). Exceptions are raised or thrown (initiated) by
either the hardware or the program itself by using a special command.

From the point of view of the author of a routine, raising an exception is a useful way to
signal that a routine could not execute normally. For example, when an input argument is
invalid (a zero denominator in division) or when a resource it relies on is unavailable
(like a missing file, or a hard disk error). In systems without exceptions, routines would
need to return some special error code

One of the problems with exception handling is knowing when and how to use it. In this
article, I will cover some of the best practices for exception handling. I will also
summarize the recent debate about the use of checked exceptions.

We as programmers want to write quality code that solves problems. Unfortunately,


exceptions come as side effects of our code. No one likes side effects, so we soon find
our own ways to get around them.

If not used correctly, exceptions can slow down your program, as it takes memory and
CPU power to create, throw, and catch exceptions. If overused,

The Nature of Exceptions

Broadly speaking, there are three different situations that cause exceptions to be thrown:

• Exceptions due to programming errors: In this category, exceptions are


generated due to programming errors (e.g., NullPointerException and
IllegalArgumentException). The client code usually cannot do anything about
programming errors.
• Exceptions due to client code errors: Client code attempts something not
allowed by the API, and thereby violates its contract. The client can take some
alternative course of action, if there is useful information provided in the
exception. For example: an exception is thrown while parsing an XML document
that is not well-formed. The exception contains useful information about the
location in the XML document that causes the problem. The client can use this
information to take recovery steps.
Exceptions due to resource failures: Exceptions that get generated when resources fail.
For example: the system runs out of memory or a network connection fails. The client's
response to resource failures is context-driven. The client can retry the operation after
some time or just log the resource failure and bring the application to a halt.

Java defines two kinds of exceptions:

• Checked exceptions: Exceptions that inherit from the Exception class are
checked exceptions. Client code has to handle the checked exceptions thrown by
the API, either in a catch clause or by forwarding it outward with the throws
clause.
• Unchecked exceptions: RuntimeException also extends from Exception.
However, all of the exceptions that inherit from RuntimeException get special
treatment. There is no requirement for the client code to deal with them, and
hence they are called unchecked exceptions.

Exception handling allows developers to detect errors easily without writing


special code to test return values. Even better, it lets us keep exception-
handling code
cleanly separated from the exception-generating code. It also lets us use the
same
exception-handling code to deal with a range of possible exceptions.

The term exception means


“exceptional condition” and is an occurrence that alters the normal program
flow.
A bunch of things can lead to exceptions, including hardware failures,
resource
exhaustion, and good old bugs. When an exceptional event occurs in Java, an
exception is said to be thrown. The code that’s responsible for doing
something
about the exception is called an exception handler, and it catches the thrown
exception.

The try is used to define a


block of code in which exceptions may occur. This block of code is called a
guarded
region (which really means “risky code goes here”). One or more catch
clauses
match a specific exception (or class of exceptions—more on that later) to a
block
of code that handles it.

This is a requirement; if you have one or more catch blocks, they must
immediately follow the try block. Additionally, the catch blocks must all
follow
each other, without any other statements or blocks in between. Also, the
order in which
the catch blocks appear matters, as we’ll see a little later.

try {
getTheFileFromOverNetwork
readFromTheFileAndPopulateTable
}
catch(CantGetFileFromNetwork) {
useLocalFileInstead
}

Try and catch provide a terrific mechanism for trapping and handling
exceptions,
but we are left with the problem of how to clean up after ourselves. Because
execution
transfers out of the try block as soon as an exception is thrown, we can’t put
our
cleanup code at the bottom of the try block and expect it to be executed if
an
exception occurs. Almost as bad an idea would be placing our cleanup code
in the
catch blocks.

A finally block encloses code that is always executed at some point after
the
try block, whether an exception was thrown or not. Even if there is a return
statement
in the try block, the finally block executes right after the return statement!
This
is the right place to close your files, release your network sockets, and
perform any
other cleanup your code requires. If the try block executes with no
exceptions, the
finally block is executed immediately after the try block completes. If
there
was an exception thrown, the finally block executes immediately after the
proper
catch block completes.

finally always runs ! OK, we’ll have to refine that a little, but for now,
start burning in the idea that finally always runs. If an exception is thrown,
finally runs.
If an exception is not thrown, finally runs. If the exception is caught, finally
runs. If
the exception is not caught, finally runs.
finally clauses are not required. If you don’t write one, your code will
compile
and run just fine.

It is illegal to use a try clause without either a catch clause or a finally


clause. A try clause by itself will result in a compiler error. Any catch
clauses must immediately follow the try block. Any finally clauses
must
immediately follow the last catch clause. It is legal to omit either the
catch
clause or the finally clause, but not both.

You might also like