Exception Handling 1. Introduction Users may use our programs in an unexpected ways. Due to design errors or coding errors, our programs may fail in unexpected.

Презентация:



Advertisements
Похожие презентации
1/27 Chapter 9: Template Functions And Template Classes.
Advertisements

© Luxoft Training 2013 Annotations. © Luxoft Training 2013 Java reflection / RTTI // given the name of a class, get a "Class" object that // has all info.
1 © Luxoft Training 2012 Inner and anonymous classes.
Inner Classes. 2 Simple Uses of Inner Classes Inner classes are classes defined within other classes The class that includes the inner class is called.
© Luxoft Training 2013 Using Reflection API in Java.
Unit II Constructor Cont… Destructor Default constructor.
Operator Overloading Customised behaviour of operators Chapter: 08 Lecture: 26 & 27 Date:
1/30 Chapter 8: Dynamic Binding And Abstract classes.
2005 Pearson Education, Inc. All rights reserved. 1 Object-Oriented Programming: Interface.
© 2009 Avaya Inc. All rights reserved.1 Chapter Two, Voic Pro Components Module Two – Actions, Variables & Conditions.
2005 Pearson Education, Inc. All rights reserved. 1 Object-Oriented Programming: Polymorphism.
Conditional Statements. Program control statements modify the order of statement execution. Statements in a C program normally executes from top to bottom,
Loader Design Options Linkage Editors Dynamic Linking Bootstrap Loaders.
A class is just a collection of variables--often of different types--combined with a set of related functions. The variables in the class are referred.
Carousel from flshow.netflshow.net by Saverio CaminitiSaverio Caminiti.
Linux Daemons. Agenda What is a daemon What is a daemon What Is It Going To Do? What Is It Going To Do? How much interaction How much interaction Basic.
HPC Pipelining Parallelism is achieved by starting to execute one instruction before the previous one is finished. The simplest kind overlaps the execution.
11 BASIC DRESS-UP FEATURES. LESSON II : DRESS UP FEATURES 12.
Arrays Dr. Ramzi Saifan Slides adapted from Prof. Steven Roehrig.
© Luxoft Training 2013 Java Collections API. © Luxoft Training 2013 Collections hierarchy.
Транксрипт:

Exception Handling 1

Introduction Users may use our programs in an unexpected ways. Due to design errors or coding errors, our programs may fail in unexpected ways during execution, or may result in an abnormal program termination It is our responsibility to produce robust code that does not fail unexpectedly. Consequently, we must design error handling into our programs. 2

Errors and Error Handling Some typical causes of errors: File system errors (i.e. disk is full, disk has been removed) Network errors (i.e. network is down, URL does not exist) Calculation errors (i.e. divide by 0) More typical causes of errors: Array errors (i.e. accessing element –1) Conversion errors (i.e. convert q to a number) 3

Exceptions What are they? An exception is a representation of an error condition or a situation that is not the expected result of a method. Exceptions are built into the Java language and are available to all program code. 4

Checked Exceptions How are they used? Exceptions fall into two categories: Checked Exceptions Unchecked Exceptions Checked exceptions are inherited from the core Java class Exception. They represent compile time exceptions that are your responsibility to check. Checked exceptions must be handled in your code. Otherwise, the compiler will issue an error message. 5

Unchecked Exceptions Unchecked exceptions are runtime exceptions that result at runtime from conditions that you should not have allowed in the first place (inherited from RuntimeException). You do not have to do anything with an unchecked exception. But, if not handled, your program will terminate with an appropriate error message. 6

Checked Exceptions 7 ExceptionDescription ClassNotFoundExceptionClass not found. CloneNotSupportedExceptionAttempt to clone an object that does not implement the Cloneable interface. IllegalAccessExceptionAccess to a class is denied. InstantiationExceptionAttempt to create an object of an abstract class or interface. InterruptedExceptionOne thread has been interrupted by another thread. NoSuchFieldExceptionA requested field does not exist. NoSuchMethodExceptionA requested method does not exist.

ExceptionDescription ArithmeticExceptionArithmetic error, such as divide-by-zero. ArrayIndexOutOfBoundsExceptionArray index is out-of-bounds. ArrayStoreExceptionAssignment to an array element of an incompatible type. ClassCastExceptionInvalid cast. IllegalArgumentExceptionIllegal argument used to invoke a method. IllegalMonitorStateExceptionIllegal monitor operation, such as waiting on an unlocked thread. IllegalStateExceptionEnvironment or application is in incorrect state. IllegalThreadStateExceptionRequested operation not compatible with current thread state. IndexOutOfBoundsExceptionSome type of index is out-of-bounds. NegativeArraySizeExceptionArray created with a negative size. NullPointerExceptionInvalid use of a null reference. NumberFormatExceptionInvalid conversion of a string to a numeric format. SecurityExceptionAttempt to violate security. StringIndexOutOfBoundsAttempt to index outside the bounds of a string. UnsupportedOperationExceptionAn unsupported operation was encountered. 8 Unchecked Exceptions

Definitions Stack trace Name of the exception in a descriptive message that indicates the problem Complete method-call stack exceptionObject.printStackTrace(); Exception message: returns a detailed message which describes the exception. exceptionObject.getMessage(); 9

Exception Handling Exception handling is accomplished through 1. the try – catch mechanism: handle the exception by yourself, 2. or by a throws clause in the method declaration: pass exception handling up the chain. If the method contains code that may cause a checked exception, you MUST handle the exception OR pass the exception up the chain. 10

Coding Exceptions Try-Catch Mechanism Wherever your code may trigger an exception, the normal code logic is placed inside a block of code starting with the try keyword: After the try block, the code to handle the exception should it arise is placed in a block of code starting with the catch keyword. If none of the code inside the try block throws an exception, then the program skips the catch clause. 11

Coding Exceptions Example try { … normal program code } catch(ArithmeticException AEx){ … } catch(Exception e) { … exception handling code } finally{ … code to close some files or release resources } 12

finally Block Consists of finally keyword followed by a block of code enclosed in curly braces Optional in a try statement This block contains code that is ALWAYS executed whether or not an exception is thrown in the corresponding try block or any of its corresponding catch blocks. If present, is placed after the last catch block Finally blocks can be used for operations that must happen no matter what (i.e. cleanup operations such as closing a file) 13

Using the throws Clause Exceptions can be thrown by statements in methods body or by methods called in methods body Exceptions can be of types listed in throws clause or subclasses 14

Coding Exceptions Passing the exception In any method that might throw an exception, you may declare the method as throws that exception, and thus avoid handling the exception yourself. You are not allowed to add more throws specifiers to a subclass method than are present in the superclass method. Example public void myMethod throws IOException { … normal code with some I/O … throw new IOException(); } 15

Example1: un-handled exception 16

Example 2: Handled Exception 17

Output of Handled Exception Example 18

Example 3 19

Output of Example 3 20

Example 4 21

Example 5 22