Você está na página 1de 25

Exception Handling

An Exception is an abnormal condition that arises in a code


sequence at run time.

A Java Exception is an object that describes an exceptional


condition that has occurred.

Exceptions can be generated by the Java-Runtime system or your


code.
class Example {
public static void main(String args[]) {
int d = 0;
int a = 42 /d;
System.out.println("a = " + a);
}
}
Exception Handling Syntax:
try {
// Code that might generate exceptions
}
catch(Type1 id1) {
// Handle exceptions of Type1
}
catch(Type2 id2) {
// Handle exceptions of Type2
}
// etc...
finally {
// Stuff that happens every time
}
Java programs have the following advantages
over traditional error management techniques:

1: Separating Error Handling Code from "Regular" Code

2: Propagating Errors Up the Call Stack

3: Grouping Error Types and Error Differentiation


Advantage 1:
Separating Error Handling Code from "Regular" Code
In traditional programming, error detection, reporting, and
handling often lead to confusing code.

In pseudo-code, a function that reads an entire file might look


something like this:
readFile {
open the file;
determine its size;
allocate that much memory;
read the file into memory;
close the file;
}
At first glance this function seems simple enough, but it
ignores all of these potential errors
What happens if the file can't be opened?
What happens if the length of the file can't be
determined?
What happens if enough memory can't be allocated?
What happens if the read fails?
What happens if the file can't be closed?

To answer these questions within your read_file function,


you'd have to add a lot of code to do error
detection,reporting and handling.
Your function would end up looking something like this:
errorCodeType readFile
{ initialize errorCode = 0;
open the file;
if (theFileIsOpen)
{
determine the length of the
file; if (gotTheFileLength)
{ allocate that much
memory; if (gotEnoughMemory)
{ read the file
into memory; if (readFailed)
{ errorCode = -1; } } else
{ errorCode = -2; } } else
{ errorCode = -3; }
close the file;
if (theFileDidntClose && errorCode == 0) {
errorCode = -4; } else { errorCode =
errorCode and -4; } } else ..
In Java the same code will look like:
readFile {
try
{
open the file;
determine its size; Actual code
allocate that much memory;
read the file into memory;
close the file;
}
Exception
catch (fileOpenFailed) { doSomething; }
code
catch (sizeDeterminationFailed) { doSomething; }
catch (memoryAllocationFailed) { doSomething; }
catch (readFailed) { doSomething; }
catch (fileCloseFailed) { doSomething; }
}
Advantage 2: Propagating Errors Up the Call Stack
The Java runtime system searches backwards through the call
stack to find any methods that are interested in handling a
particular exception. A Java method can "duck" any
exceptions thrown within it, thereby allowing a method further up
the call stack to catch it.
method1
{
try { call method2; }
catch (exception) { doErrorProcessing; }
}
method2 throws exception
{ call method3; }

method3 throws exception


{ call readFile; }
Advantage 3: Grouping Exception Types
Often exceptions fall into categories or groups.

Because all exceptions that are thrown within a Java program are
objects, grouping or categorization of exceptions is a natural
outcome of the class hierarchy.
StackOverFlowError
Throwable Error UnsatisfiedLinkerError
ArithmeticException
Exception NullPointerException
NegativeArraySizeException
InterruptedException
IndexOutOfBoundsException
RuntimeException

IOException ArrayIndexOutOfBoundsException

StringIndexOutOfBoundsException

EOFException

FileNotFoundException
Runtime exceptions represent problems that are detected by the
runtime system. This includes arithmetic exceptions (such as
when dividing by zero), pointer exceptions (such as trying to
access an object through a null reference), and indexing
exceptions (such as attempting to access an array element
through an index that is too large or too small).
Runtime exceptions can occur anywhere in a program and in a
typical program can be very numerous.
Typically, the cost of checking for runtime exceptions exceeds the
benefit of catching or specifying them. Thus the compiler does not
require that you catch or specify runtime exceptions, although you
can.
Checked exceptions represent useful information about the
operation of a legally specified request that the caller may have
had no control over and that the caller needs to be informed
about--for example, the file system is now full, or the remote end
has closed the connection.
Examples
class EX
{
public static void main(String args[])
{
int d ,a; try {

//monitor a block of code


d = 0;
a = 42 /d;
System.out.println(This will not be printed);
}
catch(ArithmeticException e) {
System.out.println(Division by Zero); }

System.out.println(After Catch);
}
public static void main(String args[]){
int x=4,y=2,z=0;
try {
z=x/y;
System.out.println("Does not Execute");
}
catch(ArithmeticException e)
{ z=0;
System.out.println(e);
}
finally
{
System.out.println("X= " +x +"Y=" +y+"Z="+z);
}
} /*
finally block is executed if exception is thrown or not */
public static void main(String args[]){
int k=0;
for(int i=0;i<4;i++) {
System.out.println("Case # "+i); try{
switch(i)
{
case 0: int x=4,y=0,z=0; z = x/y; break;
case 1: int b[]=null; k = b[0]; break;
case 2: int c[] = new int[2]; k = c[5]; break;
case 3: "abc".charAt(5); break;
} }
catch(Exception e)
{
System.out.println(e);
}
} // for
}
int k=0;
for(int i=0;i<4;i++) {
System.out.println("Case # "+i); try{
switch(i)
{ case 0: int x=4,y=0,z=0; z = x/y; break;
case 1: int b[]=null; k = b[0]; break;
case 2: int c[] = new int[2]; k = c[5]; break;
case 3: "abc".charAt(5); break;
} }

catch(NullPointerException e) {
System.out.println("It is a null pointer" + e); }
catch(IndexOutOfBoundsException e)
{ System.out.println("Index problem" + e); }
catch(Exception e)
{ System.out.println("Any type of exception" +e); }
} // for
Example for Exceptions are pushed up the Call Stack
public static void method() {
int k=0;
for(int i=0;i<4;i++) { try
{ switch(i)
{
case 3: int x=4,y=0,z=0; z = x/y; break;
case 1: int b[ ]=null; k = b[0]; break;
case 2: int c[ ] = new int[2]; k = c[5]; break;
case 0: "abc".charAt(5); break;
} }
catch(NullPointerException e) {
System.out.println("It is a null pointer" + e); }
catch(IndexOutOfBoundsException e) {
System.out.println("Index problem" + e); }
} // for
} contd
public static void main(String args[])
{
try
{
method();
}
catch(Exception e)
{
System.out.println("Any type of exception" +e);
}
}
Throwing your own Exception
class Ex {
public static void Ticket(int a) throws Exception
{
if(a>60) throw new Exception("Too old ");
else if(a<5) throw new Exception("Too young ");
System.out.println("You
will get the ticket you are" +a);
}
public static void main(String args[]) {
int ages[ ] ={24,3,78,12,4};
for(int i=0;i<ages.length;i++) try
{
Ticket(ages[i]); }
catch(Exception
e){ System.out.println(e); }
} }
Creating Your own Exception Subclasses

Define a subclass of Exception

Override String toString( ) method, allowing the


description of the exception to be displayed using
println()
class AgeException extends Exception
{ int age;
String msg;
AgeException(String m,int a)
{
msg=m;
age=a;
}
public String toString()
{
return "You are " +age + " and " +msg;
}
}
class Ex {
public static void Ticket(int a) throws AgeException
{
if(a>60) throw new AgeException("Too old ",a);
else if(a<5) throw new AgeException("Too young ",a);

System.out.println("You will get the ticket you are" +a);


}
public static void main(String args[]) { int
ages[ ] ={24,3,78,12,4};
for(int i=0;i<ages.length;i++) try
{
Ticket(ages[i]); }
catch(AgeException e){
System.out.println(e); }
}}
java.util package
Java Collection Framework
Interfaces
Implemetation classes
Utility classes

Você também pode gostar