Вы находитесь на странице: 1из 12

Managing errors and exceptions

Introduction

One of the basic features of java programming language is its robustness.


This means that errors are minimized and that errors should be properly handled.

It is common to make mistake while developing as well as typing a program.


An error may produce an incorrect output or may terminate the execution of the
program abrupty or even may cause 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 to terminate or crash during execution.

Types of errors

Errors may broadly be classified into two categories

Compile time errors


Runtime errors

Compile-time errors
All syntax errors will be detected and displayed by the java compiler an
therefore these errors are known as compile-time errors. Whenever the compiler
displays an error it will not create the .class file. Most of the errors are due to typing
mistakes. The most common mistakes are,

Missing semicolons
Missing braces in classes and methods
Misspelling of identifiers and keywords
Use of undeclared variables etc.
Missing double quotes in strings

Runtime errors

These errors are encountered after error-free compilation at the time of


execution of the program. Sometimes, a program may compile successfully creating
the class file but may not run properly. Such programs may produce wrong results
due to wrong logic or may terminate due to errors such as stack overflow. Most
common run-time erroes are.

Ex:

Dividing an integer by zero.


Accessing an element that is out of bounds of an array.
Converting invalid string to a number etc.
Attempting to use a negative size for an array.
Exceptions

An exception is a condition that is caused by a run-time error in the program.


(OR)

Errors that occur at run time are called Exceptions. An exception is simply a
runtime error. When the Java interpreter encounters an error such as dividing an
integer by zero, it creates an exceptions object and throws it(i.e. informs us that an
error has occurred.

When an exception occurs the program terminates abruptly and the control
returns to the OS. It is important to ensure that the program does not get
terminated abruptly due to the occurrence of an exception. Taking care of the
exceptions is called Exception handling. Javas exception handling feature takes
care of error handling and recovery.

Exception handling

A program should have proper exception handling mechanism. Error handling


in Java is performed with the help of an exception-handling model. The purpose of
Exception handling mechanism is to provide a means to detect and report
exceptional circumstance so that appropriate action can be taken. The
mechanism suggests incorporation of separate error handling code that performs
the following tasks:

1) Find the problem (hit the exception).


2) Inform that an error has occurred(throw the exception)
3) Receive the error information(catch the exception)
4) Take corrective actions(handle the exception)

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

The throw and exception classes are used for handling errors in Java. These
classes are derived from the Throwable, Error, Exception or any other class derived
from the object class. Only objects that are instances of Throwable, Error, Exception
or any other class derived from them are considered as exceptions by the JVMJ

The Error class exceptions are internal errors. These are rare and usually
fatal. We can not do much about them beyond notifying the user and trying to
terminate the program gracefully.

Object

Throwable
Error exception

RunTimeException

Javas built-in exceptions

Java supplies several built-in exception types that match the various sorts od
runtime errors that can be generated.

Inside the standard package java.lang java defines several exception classes.
The most general of these exceptions are subclasses of the standard type
RuntimeException. Since java.lang is implicitly imported into all java programs,
most exceptions derived from Runtime Exceptions are automatically available.

These are called checked exceptions. The following table lists exceptions and
their purposes.

Exception class Cause of exception


Exception Root class of exception hierarchy.
RuntimeException Base class for many java.lang
exceptions.
ArithmeticException Cause by math errors such as divide by
zero.
IllegalAccessException Caused when a class is not accessible.
IllegalArguementsException Caused when array size<0 or greater
than actual array size.
ArrayIndexOutOfBoundsException Caused when array size<0 or greater
than actual array size.
NullPointerException Caused when attempt to violate security
SecurityException Caused when attempt to violate security.
classNotFoundException Caused when unable to load requested
class
NumberFormatException Caused when invalid conversion of a
string to a numeric float
AWTException Caused when Exception in AWT.
IOException Root class for I/O Exceptions
FileNotFoundException Caused by an attempting to access a
nonexsistent file.
EOFException End of file exception
NoSuchMethodException Caused when requested method does
not exist
InterruptedException Caused when one thread has been
interrupted by another thread.

The Exception Handling Model


Exception handling in java is manages using five keywords

Try
catch

Throw

Throws

Finally

The general form of an exception handling is

Syntax:

Try

//block of code to monitor for errors

Catch(ExceptionType1 excep_obj)

//exception handler for exceptiontype1

Catch(Exception Type2 excep_obj)

//exception handler for exceptiontype2

Finally

//block of code to be executed finally

Here Exception Type is the type of exception that has occurred.

The try and catch statements


A try block consists of a set of executable statements that may generate an
exception. A method which may throw qa exception can also be included in the try
block. A try block can be followed by one or more catch blocks. Exception thrown
in the try block are caught in these catch blocks. A catch block must always be
associated with a try block and can not stand on its own. No statements are allowed
between try and catch blocks.

/* Arithmetic exception Demonstration*/

Class ExceptionDemo

Static int a, b,c;

Public static void main(String args[])

A=Integer.parseInt(args[0];

B=Integer.parseInt(args[0]);

Try

C=a/b;

System.out.println(division result is+c);

Catch(ArithmeticException ae)

System.out.println(division is not possible);

System.out.println(ae.toString()); //it prints system


message

Multiple catch statements


In some cases, more than one exception could be raises by a single piece of
code. To handle this type of situation, you can specify two or more catch blocks,
each catching a different type of exception. When an exception is thrown, each
catch statement is inspected in order and the first one whose type matches that of
the exception is executed. After one catch statement executes, the others are
bypassed and execution continues after the try/catch block.

Ex: /*multiple catch statements demonstration- handling multiple exceptions*/

classMultipleExceptionsDemo

Public static void main(String args[])

Int a,b,c;

Try

A=Intege.parseInt(args[0]);

B=Integer.parseInt(args[1]);

C=a/b;

System.out.println(division result is:+c);

Catch(ArrayIndexOutOfBoundsException ae)

System.out.println(no arguments given/invalid no. of


arguements);

Catch(NumberFormatException ne)

System.out.println(not a valid integer value);

}
}

Nested try-catch blocks

Sometimes a situation may arise where a part of a block may cause one error
and the entire block itself may cause another error. In such cases, we need to nest
exception handlers one within another. In java this can be done using nested try
blocks.

When nested try blocks are used, the inner try block is executed first. Any
exceptions thrown in the inner try block is caught in the corresponding catch blocks.
If a matching catch block is not found, then catch blocks of the outer try blocks are
inspected. If no matching blocks found, then the JRE handles the exception.

Ex: /*nested try catch demo*/

Class NestedTryDemo

Public static void main(String args[])

Try

Int num=args.length;

Try

Int numvalue=Integer.parseInt(args[0]);

System.out.println(the square
is:+numvalue*numvalue);

Catch(NumberFormatException nb)

System.out.println(not a number);

}
Catch(ArrayIndexOutOfBoundsException e)

System.out.println(no argument given);

The finally block

Sometimes there may be cleanup codes, which are required to be executed.


However, whenever an exception occurs, the program halts abruptly and the
cleanup code gets executed. To deal with this, Java provides to finally block.

The finally block ensures that all cleanup work is taken care if when an
exception occurs. It is used in conjunction with a try block. The finally block contain
statements that either return resources to the system or print message. A finally
block must always be associated with a try block and can not stand on its own. The
finally block is guaranteed to run whether or not an exception occurs, the finally
clause of a try catch block will always execute, even if there are any return
statement in the try catch part.

Ex:/*finally block demonstration*/

Class FinallyDemo

String name;

Int one,two;

FinallyDemo(String args[])

Try

Name=new String(Excel computers);

One=Integer.parseInt(args[0]);

Two=Integer.parseInt(args[1]);
System.out.println(name:+name);

System.out.println(division result:+one/two);

Catch(ArithmeticException e)

System.out.println(cant divide by zero);

Finally

Name=null;//cleanup code

System.out.println(finally executed);

Public static void main(String args[])

New FinallyDemo(args);

Throw keyword

Exceptions are thrown with the help of the throw keyword. The throw
keyword is used to throw an exception explicitly.
The general form of throw keyword is

Throw throwable_instance;

Here throwable instance must be an object or type Throwable or a subclass of


Throwable.

Ex:/*throw keyword demonstration*/

Class ThrowDemo
{

Public static void main(String args[])

Try

If(args.length==0)

Throw new NullPointerException();

System.out.println(args.length+elements are present in args);

Catch(NullPointerException e)

System.out.println(arguments not given);

Throws keyword

If a method is capable of causing an exception that it does not handle, it must


specify this behavior so that callers of the method can guard themselves against
that exception. We do this by including a throws clause in the method declaration.
A throws clause lists the types of exceptions that a method might throw. This is
necessary for all exceptions except those of type Error or RuntimeException or
any subclasses of them. All other exceptions that a method can throw must be
declared in the throws clause.

The general form of the usage of the throws keyword is

Type method_name(para_list) throws Exception_list

//body of the method.

}
Here Exception list is a common seperated list of the exceptions that a method can
throw.

User defined Exceptions or creating our own Exceptions

Built-in exceptions provided by the Error and Exception classes may not
always be enough to trap occurring in a program. Hence there is a need for user
defined exception class. A user Defined exception class should be a subclass of the
Exception class. The Exception class does not define any methods of its own but
inherits methods from Throwable. Therefore, any user defined exception class also
inherits methods of Throwable. In addition it may define methods of its own. The
advantage of sub classing the Throwable. In addition it may define methods of its
own. The advantage of sub classing the Exception class is that, the new Exception
type can be caught separately from other subclasses of Throwable.

/* program to demonstrate user defined exception*/

Class ArraySizeException extends Exception

ArraySizeException() //constructor

super(you have passed illegal array size);

Class MyExceptionDemo

Int size,array[];

MyExceptionDemo(int s)

size=s;

try

Checksize();

}
Catch(ArraySizeException e)

System.out.println(e);

Void checksize() throws ArraySizeException

If(size<0)

Throw new ArraySizeExceptiom();

Array=new int[size];

For(int i=0,k=0;i<size;i++)

Array[i]=k++;

System.out.println(array[i]);

Public static void main(String a[])

New MyExceptionDemo(Integer.parseInt(a[0]));

Вам также может понравиться