Managing Errors and Exception
Managing Errors and Exception
Introduction
Types of 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
Ex:
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
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
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.
Try
catch
Throw
Throws
Finally
Syntax:
Try
Catch(ExceptionType1 excep_obj)
Finally
Class ExceptionDemo
A=Integer.parseInt(args[0];
B=Integer.parseInt(args[0]);
Try
C=a/b;
Catch(ArithmeticException ae)
classMultipleExceptionsDemo
Int a,b,c;
Try
A=Intege.parseInt(args[0]);
B=Integer.parseInt(args[1]);
C=a/b;
Catch(ArrayIndexOutOfBoundsException ae)
Catch(NumberFormatException ne)
}
}
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.
Class NestedTryDemo
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)
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.
Class FinallyDemo
String name;
Int one,two;
FinallyDemo(String args[])
Try
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)
Finally
Name=null;//cleanup code
System.out.println(finally executed);
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;
Class ThrowDemo
{
Try
If(args.length==0)
Catch(NullPointerException e)
Throws keyword
}
Here Exception list is a common seperated list of the exceptions that a method can
throw.
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.
ArraySizeException() //constructor
Class MyExceptionDemo
Int size,array[];
MyExceptionDemo(int s)
size=s;
try
Checksize();
}
Catch(ArraySizeException e)
System.out.println(e);
If(size<0)
Array=new int[size];
For(int i=0,k=0;i<size;i++)
Array[i]=k++;
System.out.println(array[i]);
New MyExceptionDemo(Integer.parseInt(a[0]));