Está en la página 1de 27

NAME:ISHAN GHOSH STREAM:ELECTRONICS AND COMMUNICATION ENGINEERING COLLEGE:KANAD INSTITUTE OF ENGINEERING AND MANAGEMENT,MANKAR.

ROLL NO:O8ECE011,08252003014 YEAR:2008-2012

3/5/12

EXCEPTION HANDLING IN JAVA

3/5/12

INTRODUCTION

Errors are a normal part of programming.Some of these errors are flaws in a program's basic design or implementation--these are called bugs.Other types of errors are not really bugs; rather, they are the result of situations like low memory or invalid filenames.The way we handle the second type of error determines whether they become 3/5/12 bugs.Java's exception-handling

WHAT IS AN EXCEPTION?

As the name implies, an exception is an exceptional condition. An exception is something out of the ordinary. Most often, exceptions are used as a way to report error conditions.Exceptions provide notification of errors and a way to handle them. This control structure allows us to specify exactly where to handle specific types of errors.
3/5/12

IF EXCEPTIONS THAN?

The most common means of error checking is the function's return value. Consider the problem of calculating the retail cost of an item and displaying it. For this example, the retail cost is twice the wholesale cost:

int retailCost( int wholesale ) 3/5/12 {

THE EXCEPTION HANDLING TECHNIQUE


Involves the use of the try, catch, and finally Java keywords. Consists of several steps:
1.

try a block of code that may result in an exception being "thrown"

2.

Code one or more blocks designed to automatically catch and handle a specific type of exception if one occurs. At most, only one of these blocks can be called in a single pass 3/5/12 through the code. If none of the

Has the following general syntax:

try { statements that may result in an exception being thrown; } catch (exception-type1 reference) { statements to handle the exception; }

catch (exception-type2 reference) 3/5/12 {

SOME TERMINOLOGY

Exception handling can be viewed as a nonlocal control structure. When a method throws an exception, its caller must determine whether it can catch the exception. If the calling method can catch the exception, it takes over and execution continues in the caller.Java exceptions are class objects subclassed from java.lang.Throwable. Because exceptions are class objects, they 3/5/12 can contain both data and methods.

THROW AN EXCEPTION

The method instantiates an object of type Exception. The Exception constructor takes a String parameter. The string contains a message that can be retrieved when the exception is caught. The throw statement terminates the method and gives its caller the opportunity to catch it: if( correct > total )

3/5/12

it must be placed within a try block.A try block is a block of code beginning with the try keyword followed by a left and right curly brace. Every try block is associated with one or more catch blocks. Here is a try block: { // method calls go here } If a method is to catch exceptions thrown by the methods it calls, the calls must be placed within a try block.If an exception is thrown, it is handled in a catch block. Different catch blocks handle different types of exceptions.This is a try block and a catch block set up to handle exceptions of type Exception: { // method calls go here } catch( Exception e ) 3/5/12 { try try

THROW,TRY AND CATCH BLOCKS method that produces To respond to an exception, the call to the

When any method in the try block throws any type of exception, execution of the try block ceases. Program control passes immediately to the associated catch block. If the catch block can handle the given exception type, it takes over. If it cannot handle the exception, the exception is passed to the method's caller. In an application, this process goes on until a catch block catches the exception or the exception reaches the main() method uncaught and causes the application to terminate.

3/5/12

An example:
import java.io.* ; import java.lang.Exception ; public class gradeTest { public static void main( String[] args ) { try { // the second call to passingGrade throws // an excption so the third call never Click to // gets executed edit Master subtitle style System.out.println( passingGrade( 60, 80 ) ) ; System.out.println( passingGrade( 75, 0 ) ) ; System.out.println( passingGrade( 90, 100 ) ) ; }

3/5/12

catch( Exception e ) { System.out.println( "Caught exception --" + e.getMessage() ) ; } } static boolean passingGrade( int correct, int total ) throws Exception { } boolean returnCode = false ; if( correct > total ) { throw new Exception( "Invalid values" ) ; } if ( (float)correct / (float)total > 0.70 ) { returnCode = true ; } return returnCode ; }
3/5/12

Output

The second call to passingGrade() fails in this case because the method checks to see whether the number of correct responses is less than the total responses. When passingGrade() throws an exception, control passes to the main() method. In the example, the catch block in main() catches the exception and prints Caught exception - Invalid values. 3/5/12

MULTIPLE CATCH BLOCKS

In some cases, a method may have to catch different types of exceptions. Java supports multiple catch blocks. Each catch block must specify a different type of exception: try { // method calls go here } catch( SomeExceptionClass e ) { 3/5/12 // handle SomeExceptionClass

A method that ignores exceptions thrown by the method it calls. import java.io.* ; import java.lang.Exception ; public class MultiThrow { public static void main( String[] args ) { try { fool() ; } catch( Exception e ) 3/5/12

A method that catches and rethrows an exception. import java.io.* ; import java.lang.Exception ; public class MultiThrowA { public static void main( String[] args ) { try { fool() ; } catch( Exception e ) 3/5/12

THE FINALLY CLAUSE

Java introduces a new concept in exception handling: the finally clause. The finally clause sets apart a block of code that is always executed.Example of a finally clause: import java.io.* ; import java.lang.Exception ; public class MultiThrowFin { public static void main( String[] 3/5/12 args )

THE THROWABLE CLASS

All exceptions in Java are subclassed from the class Throwable.If we want to create your own exception classes, we must subclass Throwable. Most Java programs do not have to subclass their own exception classes.Following is the public portion of the class definition of Throwable: public class Throwable { 3/5/12

Java exceptions are Throwable objects (they are instances of Throwable or a subclass of Throwable). The Java packages contain numerous classes that derive from Throwable and thus, build a hierarchy of Throwable classes.

3/5/12

TYPES OF EXCEPTIONS

The methods of the Java API and the language itself also throw exceptions. These exceptions can be divided into two classes: Exception and Error. Both the Exception and Error classes are derived from Throwable.Exception and its subclasses are used to indicate conditions that may be recoverable. 3/5/12

Java.awt Exceptions:

DIFFERENT LIST OF EXCEPTION

The AWT classes have members that throw one error and two exceptions: AWTException (exception in AWT) llegalComponentStateException (a component is not in the proper state for a requested operation) AWTErr (error in AWT)
3/5/12

java.awt.datatransfer Exception:

java.io Exceptions: The classes in the java.io package throw a variety of exceptions, Any classes that work with I/O are good candidates to throw recoverable exceptions. For example, activities such as opening files or writing to files are likely to fail from time to time. The classes of the java.io package do not throw errors at all. java.lang Exceptions: The java.lang package contains much of
3/5/12

java.rmi Error: The Java Remote Method Invocation classes allow Java objects to exist on remote machines. These classes throw the following error: ServerError (remote server indicates error) java.rmi Exceptions: Java objects whose methods are invoked remotely through RMI may throw exceptions. 3/5/12

java.security.acl Exceptions: The Java security access control list API allows Java developers to control access to specific users. The classes of java.security.acl throw the following exceptions: ACLNotFoundException (unable to find access control list) LastOwnerExcepti (attempt to delete last owner of ACL) NotOwnerExcepti (only the owner may modify) java.sql Exceptions: The Java SQL API throws the following exceptions: DataTruncation (unexpected data truncation) SQLException (SQL error--contains detailed SQL information) SQLWarning (SQL warning) java.util Exceptions: The classes of the java.util package throw the following exceptions: EmptyStackException (no objects on stack) MissingResourceException (resource missing) NoSuchElementException (no more objects in collection)

3/5/12

BUILT-IN EXCEPTIONS

Here application creates a method and forces it to divide by zero. The method does not have to explicitly throw an exception because the division operator throws an exception when required.An example of a built-in exception.

import java.io.* ; import java.lang.Exception ; 3/5/12

Output: The output of this application is shown here:2/3 = 0 Caught exception / by zeroThe first call to div() works fine. The second call fails because of the divide-byzero error. Even though the application did not specify it, an exception was thrown--and caught.

3/5/12

También podría gustarte