Download Exception-Handling Fundamentals

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Exception-Handling Fundamentals
A Java exception is an object that describes an
exceptional (that is, error) condition that has occurred in
a piece of code.
When an exceptional condition arises, an object
representing that exception is created and thrown in the
method that caused the error. That method may choose to
handle the exception itself, or pass it on. Either way, at
some point, the exception is caught and processed.
Contd…..
 Exceptions can be generated by the Java run-time system,
or they can be manually generated by your code.
 Exceptions thrown by Java relate to fundamental errors
that violate the rules of the Java language or the
constraints of the Java execution environment. Manually
generated exceptions are typically used to report some
error condition to the caller of a method.
 Java exception handling is managed via five keywords: try,
catch, throw, throws, and finally.
Exception-Handling Block
try {
// block of code to monitor for errors
}
catch (ExceptionType1 exOb) {
// exception handler for ExceptionType1
}
catch (ExceptionType2 exOb) {
// exception handler for ExceptionType2
}
finally {
// block of code to be executed before try block ends
}
Exception Types
 All exception types are subclasses of the built-in class
Throwable. Thus, Throwable is at the top of the exception class
hierarchy.
 Immediately below Throwable are two subclasses that partition
exceptions into two distinct branches. One branch is headed by
Exception.
 This class is used for exceptional conditions that user
programs should catch. This is also the class that you will
subclass to create your own custom exception types.
 There
is
an
important
subclass
of
Exception,
called
RuntimeException.
 Exceptions of this type are automatically defined for the
programs that you write and include things such as division by
zero and invalid array indexing.
 The other branch is topped by Error, which defines exceptions
that are not expected to be caught under normal circumstances
by your program.
 Exceptions of type Error are used by the Java run-time system
to indicate errors having to do with the run-time environment,
itself. Stack overflow is an example of such an error.
Uncaught Exceptions
Before you learn how to handle exceptions in your program, it is useful
to see what happens when you don’t handle them. This small program
includes an expression that intentionally causes a divide-by-zero error.
Class error1
{
public static void main( String args[ ])
{
int a=10;
int b=5;
int c=5;
int x=a/(b-c);
System.out.println(“x” +x);
int y= a/(b+c);
System.out.println(“y” +y);
} }
Using try-catch block
Class error2
{
public static void main( String args[ ])
{ int a=10;
int b=5;
int c=5;
int x, y;
try
{
x= a/( b-c);
}
Catch (AirthmeticException e)
{
System.out.println(“division by Zero”);
}
y=a/(b+c);
System.out.println(“y” +y);
}
}
Why do I have put an f after a floating
point constants
• The f suffix directs the compiler to create a float
value a sequence of characters representing a
floating point number (a float literal) – otherwise
the compiler would by default create either a
double value or an int value.
Multiple catch Clauses
• In some cases, more than one exception could be raised by
a single piece of code. To handle this type of situation, you
can specify two or more catch clauses, 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.
Multiple Catch Statements
try
{ statement; // generates an exception
}
catch (Exception_type-1 e)
{ Statement; }
catch (Exception_type-2 e)
{ Statement; }
Catch (Exception_type-3 e)
{ Statement;}
Multiple Catch statements
class multicatch
{
public static void main( String args[ ])
int a [ ] = {5, 10};
int b=5;
try {
int x= a[2] /b-a[1]; }
catch( ArithmaticException e)
{
System.out.println(“Division by Zero”);
}
catch( ArrayIndexOutOfBoundsException e)
{
System.out.println(“array index array”);
}
catch( ArrayStoreException e)
{
System.out.println(“ Wrong Data type”);
}
Nested try statement
• The try statement can be nested. That is, a try statement
can be inside the block of another try. Each time a try
statement is entered, the context of that exception is
pushed on the stack. If an inner try statement does not
have a catch handler for a particular exception, the stack is
unwound and the next try statement’s catch handlers are
inspected for a match. This continues until one of the catch
statements succeeds, or until all of the nested try
statements are exhausted. If no catch statement matches,
then the Java run-time system will handle the exception.
Nested try statements
class nestTry
{ public static void main( String args[ ])
try {
int a= args.length;
int b= 42/a;
System.out.println(“ a” +a);
try {
if(a==1)
a=a/(a-a);
Contd……
If(a==2)
{
int c[ ]= {1};
c[42]=99;
} }
catch(ArrayIndexOutOfBoundsException e)
{ System.out.println(“ Array index out of bounds” +e)
}
Catch((AirthmaticException e) {
System.out.println(“ divided by 0:” +e);
} }
}
throw statement
So far, We have only been catching exceptions that
are thrown by the java run-time system. However, it
is possible for your program to throw statement. The
syntax is:
throw ThrowableInstance;
Throwableinstance must be an object of type
throwable or subclass of Throwable.
Example of throw statement
Class throwdemo
{
static void demoproc()
{ try {
throw new NullPointerException(“demo”)
}
Catch(NullPointerException e){
System.out.println(“caught inside demoproc”);
Throw e; // rethrow the exception
} }
Contd………..
public static void main( String s[ ])
{
try {
demoproc();
}
catch(NullPointerException e)
{
System.out.println(“Recaught” +e);
} }
}
Output
Caught inside demoproc.
Recaught: java.lang.NullPointerException:demo
Finally statement
Finally statement is used to handle an
exception that is not caught by any of the
catch statements. Finally block can be used
to handle any exception generated within a
try block. It may be added immediately
after the try block or after the last catch
block.
Syntax of finally statement
try
{ ……….
……….
}
finally {
……….
………..
}
try
{ ……….
……….
}
catch ( ….)
{
}
finally{
………
}
Use of Interface
1. To incorporate multiple inheritence in
Java Application.
2. To Develop Distributed applications.
Difference between java and java script
• Java language can stand on its own and creates
"standalone" applications while JavaScript must
be placed inside an HTML document to function.
• Java must be compiled into what is known as a
"machine language" before it can be run. You can
alter JavaScript that are in an HTML document
after it runs and run it again and again. If you
alter java program you need to compile it again
before run.
Creating Your Own Exception Subclasses
• Although Java’s built-in exceptions handle most
common errors, you will probably want to create your
own exception types to handle situations specific to
your applications.
• This is quite easy to do: just define a subclass of
Exception. Your subclasses don’t need to actually
implement anything—it is their existence in the type
system that allows you to use them as exceptions.
Creating and throwing your own exception
import java.lang.Exception;
class myexception extends Exception
{
myexception(String message)
{
super(message);
}
class testmyexcp
{ public static void main(Strings args[ ])
{ int x=5, y=1000;
try {
float z=(float) x/ (float) y;
if( z < 0.01)
{
Contd….
throw new myexception(“number is too small”);
} }
catch (myexception e)
{ System.out.println(“caught my exception”);
System.out.println(e.getmessage( ) );
}
finally
{ system.out.println(“ I m always here”);
} } }
}
Java’s Built-in Exceptions