introduction types of errors exceptions exception handling common java exceptions syntax of...

Post on 01-Apr-2015

269 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

TRANSCRIPT

Topics Introduction

Types of Errors

Exceptions

Exception Handling

Common JAVA Exceptions

Syntax of Exception Handling Code

Example: Divide by Zero without

Exception Handling

Example: Handling Arithmetic

Exception

Example: Multiple Catch Statement

Java Exception Hierarchy

Finally Block

Example with finally block

Using throw Keyword

Example

Introduction

An error may produce an incorrect output or may terminate the execution of the program abruptly or even may cause the system to crash.

it is therefore important to detect and manage properly all the possible error conditions in the program so that the program will not terminate or crash during execution.

Types of Errors

Errors may broadly be classified into two categories. They are

Compile – Time errorsAll syntax errors will be detected and displayed by the JAVA compiler and therefore these errors are known as compile – time errors. Most of the compile – time errors are due to typing mistakes. The most common error are.

Missing semicolons Missing brackets in classes and methods Misspellings of identifiers and keywords Missing double quotes in strings Use of undeclared variables Incompatible types in assignments / initializations use of = in place of == operator And so on.

Types of Errors

Errors may broadly be classified into two categories. They are

Run – Time errorsAfter compilation process is completed, the program has to be tested for various inputs. If the program produce wrong results due to wrong logic or may terminate due to errors. Such errors are called Run – Time errors. Most common run – time errors are.

Diving an integer by 0. Accessing an element that is out of bounds of an array. Attempting to use a negative size for an array. Trying to store a value of an incompatible types. Converting invalid String to a number Accessing a character that is out of bounds of a String. And many more.

When such errors are encountered, java typically generates an error message and aborts the program

Exceptions

An Exception is a condition that is caused by a run – time error in the program.

When JAVA interpreter encounters an error, it creates an Exception object and throws it.

if the exception object is not caught and handled properly, the interpreter will display an error message and will terminate the program.

if the programmer want the program to continue with execution of the remaining code, then the programmer should try to catch the exception object thrown by the error condition and then display an appropriate message for taking corrective

actions. This task is known as Exception Handling.

Exception Handling

The purpose of Exception Handling mechanism is to provide a means to detect and report an “Exception Circumstance” so that appropriate action can be taken. Exception Handling performs the following tasks

Find the problem (HIT the exception). Inform that an error has occurred (THROW the exception). Receive the error information (CATCH the exception). Take corrective actions (HANDLE the exception).

The exception handling code basically consists of two segments. One to detect error and to throw exceptions and the other to catch exception and to take appropriate actions.

Common Java Exceptions

The programmer always be on the lookout for places in the program where exception could be generated. Some common exceptions that we must watch out for catching are listed.

Exception Type Cause of ExceptionArithmeticException Caused by math errors such as division by zero

ArrayIndexOutOfBoundException Caused by bad array indexes

ArrayStoreException Caused when a program tries to store the wrong type of data in an array

FileNotFoundException Caused by an attempt to access a nonexistent file

NullPointerException Caused by referencing a null object

NumberFormatException Caused when a conversion between strings and numbers fails

StackOverFlowException Caused when the system runs out of stack space.

Syntax of Exception Handling

The basic concepts of exception handling are throwing an exception and catching it. This is illustrated in figure as shown.

try block

Statement that causes an exception

catch block

Statement that handles the exception

Exception object creator

Exception handler

Throws exception object

Syntax of Exception Handling

Java uses the keyword try to preface a block of code that is likely to cause an error condition throw an exception.

A catch block defined by the keyword catch, catches the exception thrown by the try block and handles it appropriately.

The catch block is added immediately after the try block.

try block{ statement;}catch(Exceptiontype ex){ statement;}

the try block can have one or more statements that could generate an exception, the remaining statements in the block are skipped and execution jumps to the catch block.

The catch block too can have one or more statements that are necessary to process the exception.

Example: Divide by Zero without Exception

Example: Divide by Zero without Exception

Output:

Example: Handling Arithmetic Exception

Example: Handling Arithmetic Exception

Output:

Example: Multiple Catch Statements

Output:

Example: Multiple Catch Statements

Output:

Example: Multiple Catch Statements

Output:

Example: Multiple Catch Statements

Java Exception Hierarchy

Exception classes inherit directly or indirectly from class Exception, forming an inheritance hierarchy.

Can extend this hierarchy with your own exception classes.

Figure  shows a small portion of the inheritance hierarchy for class Throwable (a subclass of Object), which is the superclass of class Exception.

Only Throwable objects can be used with the exception-handling mechanism.

Class Throwable has two subclasses: Exception and Error.

Java Exception Hierarchy

Finally Block

The finally block always executes when the try block exits. This ensures that the finally block is executed even if an unexpected exception occurs. But finally is useful for more than just exception handling.

it allows the programmer to avoid having cleanup code accidentally bypassed by a return, continue, or break. Putting cleanup code in a finally block is always a good practice, even when no exceptions are anticipated.

The finally block is used for resource de-allocation.

Placed after the last catch block.

Example: With Finally Block

Output:

Throwing Our own Exceptions

The uses can do by using the keyword throw as follows

throw new Throwable_subClass;

Example:throw new ArithmeticException();throw new NumberFormatException();

Example using Throw

Example using Throw

Output:

?

top related