1 / 49

EXCEPTIONS

EXCEPTIONS. Definition. A java exception is an object that describes an exceptional condition that has occurred in a piece of code. Or It is an abnormal condition that arises in a code sequence at run time. Exception.

akira
Download Presentation

EXCEPTIONS

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. EXCEPTIONS

  2. Definition • A java exception is an object that describes an exceptional condition that has occurred in a piece of code. Or • It is an abnormal condition that arises in a code sequence at run time.

  3. Exception An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions. In a language without exception handling: When an exception occurs, control goes to the operating system, where a message is displayed and the program is terminated In a language with exception handling: Programs are allowed to trap some exceptions, thereby providing the possibility of fixing the problem and continuing

  4. Introduction to Exception Handling • Many languages allow programs to trap input/output errors (including EOF) • Def: An exception is any unusual event, either erroneous or not, detectable by either hardware or software, that may require special processing • Def: The special processing that may be required after detection of an exception is called exception handling • Def: The exception handling code unit is called an exception handler

  5. Introduction to Exception Handling • Def: An exception is raised when its associated event occurs • A language that does not have exception handling capabilities can still define, detect, raise, and handle exceptions (user defined, software detected)

  6. Introduction to Exception Handling • Advantages of Built-in Exception Handling: 1. Error detection code is tedious to write and it clutters the program 2. Exception propagation allows a high level of reuse of exception handling code

  7. Introduction to Exception Handling • Design Issues for Exception Handling: 1. How and where are exception handlers specified and what is their scope? 2. How is an exception occurrence bound to an exception handler? 3. Where does execution continue, if at all, after an exception handler completes its execution? 4. How are user-defined exceptions specified?

  8. Introduction to Exception Handling • Design Issues for Exception Handling: 5. Should there be default exception handlers for programs that do not provide their own? 6. Can built-in exceptions be explicitly raised? 7. Are hardware-detectable errors treated as exceptions that can be handled? 8. Are there any built-in exceptions? 9. How can exceptions be disabled, if at all?

  9. Exception-Handling Control Flow

  10. When an error occurs within a method, the method creates an object and hands it off to the runtime system. The object, called an exception object, contains information about the error, including its type and the state of the program when the error occurred. Creating an exception object and handing it to the runtime system is called throwing an exception. • After a method throws an exception, the runtime system attempts to find something to handle it. The set of possible "somethings" to handle the exception is the ordered list of methods that had been called to get to the method where the error occurred. The list of methods is known as the call stack

  11. The runtime system searches the call stack for a method that contains a block of code that can handle the exception. This block of code is called an exception handler.

  12. The Java runtime system requires that a method either catch or specify all checked exceptions that can be thrown by that method. checked exceptions that can be thrown by that method. This requirement has several components — "catch," "specify," "checked exceptions," Catch • A method can catch an exception by providing an exception handler for that type of exception. Specify • A method specifies that it can throw exceptions by using the throws clause in the method declaration.

  13. Checked Exceptions • There are two kinds of exceptions: • runtime and nonruntime. • Runtime exceptions occur within the Java runtime system: • arithmetic exceptions • dividing by zero; • pointer exceptions, null reference; • indexing exceptions,

  14. Nonruntime exceptions • are exceptions that occur in code outside of the Java runtime system. • exceptions that occur during I/O are nonruntime exceptions. • The compiler ensures that nonruntime exceptions are caught or specified; thus, they are also called checked exceptions.

  15. Exceptions that Can Be Thrown Within the Method's Scope The exceptions that a method can throw include the following: ·         Any exception thrown directly by the method with the throw statement ·         Any exception thrown indirectly by calling another method that throws an exception

  16. Catching and Handling Exceptions • throwsDescribes the exceptions which can be raised by a method. • throwRaises an exception to the first available handler in the call stack, unwinding the stack along the way. • tryMarks the start of a block associated with a set of exception handlers. • catchIf the block enclosed by the try generates an exception of this type, control moves here; • finallyAlways called when the try block concludes, and after any necessary catch handler is complete.

  17. Steps of try…catch…finally • Every try block must have at least one catch or finally block attached. try { Code } catch and finally blocks . . . • If an exception is raised during a try block: • The rest of the code in the try block is skipped over. • If there is a catch block of the correct, or derived, type in this stack frame it is entered. • If there is a finally block, it is entered. • If there is no such block, the JVM moves up one stack frame.

  18. try { } catch (FileNotFoundException e) { System.err.println("FileNotFoundException: " + e.getMessage()); } catch (IOException e) { System.err.println("Caught IOException: " + e.getMessage()); }

  19. class trow_clause { public static void main (string args[] ) { try { throw new NullPointerException() }catch (NullPointerException e) { System.out.println(“Invalid Reference”); } } }

  20. The finally Block • The final step in setting up an exception handler is to clean up before allowing control to be passed to a different part of the program. • Do this by enclosing the cleanup code within a finally block. • The finally block is optional and provides a cleanup mechanism regardless of what happens within the try block. • Use the finally block to close files or to release other system resources.

  21. finally { if (out != null) { System.out.println("Closing PrintWriter"); out.close(); } else { System.out.println("PrintWriter not open"); } }

  22. Error Class When a dynamic linking failure or other hard failure in the Java Virtual Machine occurs, the virtual machine throws an Error. Simple programs typically do not catch or throw Errors. Exception Class Most programs throw and catch objects that derive from the Exception class. • The Java platform defines the many descendants of the Exception class. IllegalAccessExceptionNegativeArraySizeException

  23. Exception handling block try{ // block of code of monitor for errors } catch(exception type){ // exceptionhandler for exception type } //////// finally{ //block of code to be executed before try block ends }

  24. Types of exceptions An exception is always an object of some subclass of standard class “ throwable”. • Error • Exceptions

  25. Error exception • These exceptions are defined by the error class. • These types of excepton errors can not be expected to catch.

  26. Exception classes • ArithmaticException • IndexoutofBoundsExceptions • NegativeArraySizeException • NullPointerException • ArrayStoreException • SecurityException • IllegalmonitorStateException • IlligalStateException

  27. Handle error Exceptions • Return to the safe state and enable the user to execute other commands; OR • Allow the user to save all his work and terminate the program gracefully.

  28. Handling Exceptions Five kinds of code blocks in a method to handle them i.e • try block • catch block • throw • throws • finally block

  29. The try block • When you want to catch an exception,the code in the method that might cause the exception to be thrown must be enclosed in a try block. Code that can cause exceptions need not be in try block. • A try block is simply the keyword “try”, followed by braces enclosing the code that can throw the exception: SYNTAX:- try{ //code that can throw one or more exceptions }

  30. The catch Block • The catch block must immediately follow the try block that contains the code that may throw the particular exception. • A catch block consists of the keyword catch followed by a single parameter between parentheses that identifies the type of exception that the block is to deal with. • This is followed by the code to handle the exception enclosed between braces.

  31. try { // code that can throw one or more exception } catch(ArithmeticException e) { // code to handle the exception }

  32. TRY AND CATCH BLOCK public class TestTryCatch { public static void main(string[ ] args ) { int I = 1; int j = 0; Try { System .out.println(“Try block entered ”+ “I = “+ I + ” j = “+ j); System .out .println(I/j); //Divide by 0 – exception thrown System .out.println(“Ending try block”); } catch(Arithmeticexception e) { //catch the exception System .out.println(“Arithmetic exception caught”) ; } System.out.println(“After try block”) ; } }

  33. OUT PUT Try block entered I = 1 j = 0 Arithmetic exception caught After try block

  34. USING TRY AND CATCH Class Exc2 { Psvm(String args[]) { Int d,a; Try { //monitor a block of code. d=0; a=42/d; sop(“this will not printed”); }catch(ArithmaticException e) { //catch divide by zero error sop(“division by zero”); } Sop(“after catch statement.”); } }

  35. Output Division by zero After catch statement

  36. throw There are two ways you can obtain a throwable object: using a parameter into a catch clause, or creating one with the new operator. • It is possible for your program to throw an exception explicitly, using the throw statement • The general form of throw is shown here :- throw throwableinstance; • Throwableinstance must be an object of type throwable or subclass of throwable.simple types,such as int or char,as well as non-throwable classes, such as string and object,cannot be used as exceptions.

  37. // Demonstrate throw. Class throwdemo { static void demoproc() { Try { Throw new nullpointerexception(“demo”) ; } catch (nullpointerexception e) { System.out.println(“caught inside demoproc.”); Throw e; // rethrow the exception } } Public static void main (string args[] ) { try { demoproc (); } catch(nullpointerexception e) { System.out.println(“recaught : “ + e); } } }

  38. OUTPUT Caught inside demoproc. Recaught : java.lang.nullpointerException : demo

  39. throws • A throws clause lists the type of exceptions that a method might throw . • This is necessary for all exceptions,except those of type error or runtimeexception,or any of their subclasses. • All other exception that a method can throw must be declared in the throws clause. • If they are not a compile-time error will result. • The general form is Type method-name(parameter-list)throws exception- list { //body of method }

  40. Class throwsDemo { static void throwone () throws illegalaccessexception { system.out.println (“ inside throwone.”) ; Throw new illegalaccessException (“demo”) ; } Public static void main (string args [ ] ) { Try { throwOne ( ); } catch (illegalAccessException e) { System . Out . Print In ( “ caught “ + e ) ; } } }

  41. OUPUT Inside throwone Caught java.lang.illegalaccessException : demo

  42. Finally • Finally creates a block of code that will be executed after a try/catch block has completed and before the code following the try/catch block. • The finally block will execute whether or not an exception is thrown. • If an exception is thrown,the finally block will execute even if no catch statement matches the exception.

  43. Class finallydemo { //through an exception out of the method. Static void procA() { try { system.out.println(“inside procA”) ; throw new runtimeException(“demo”) ; } finally {system.out.println(“procA’s finally”) ;} } // return from within a try block. Static void procB () { try {system.out.println(“inside procb” ); return ;} finally {system.out.println( “procB’s finally” ) ; } }

  44. //Executea try block normally. Static void proc () { try { system.out.println(“inside procC “) : } finally { system.out.println(“procC’s finally”) ; } } Public static void main(string args[ ] ) { try { procA ( ); } catch (Exception e) { system.out.println(“exception caught”) ; } procB ( ); procC ( ); } }

  45. Out put Inside procA procA’s finally Exception caught Inside procB procB’s finally Inside procC procC’s finally

  46. Exception subclasses • The exception class does not define any methods of its own. • It does, of course,inherit those methods provided by throwable. • Thus,all exceptions, including those that you create,have the methods defined by throwable available to them.

  47. Method Throwable fillinStackTrace ( ) String getLocalizedMessage() String getMessage( ) Void printStackTrace ( ) Void printStackTrace(printStrea stream) Void printStackTrace(printWritr stream) String tostring( ) Description Returns a Throwable object that contains a completed stacktrace.This object can be rethrow. Returns a localized description of the exception. Returns a description of the exception Displays the stack trace. Sends the stack trace to the specified stream. Sends the stack trace to the specified Stream. Returns a String object containing a description of the exception.this Method is called by println()when Outputting a Throwable object.

More Related