Chapter 5. Exceptions. CSC 113 King Saud University College of Computer and Information Sciences Department of Computer Science. Dr. S.

Size: px
Start display at page:

Download "Chapter 5. Exceptions. CSC 113 King Saud University College of Computer and Information Sciences Department of Computer Science. Dr. S."

Transcription

1 Chapter 5 Exceptions CSC 113 King Saud University College of Computer and Information Sciences Department of Computer Science Dr. S. HAMMAMI

2 Objectives After you have read and studied this chapter, you should be be able to to Improve the the reliability of of code by by incorporating exception-handling and and assertion mechanisms. Write methods that that propagate exceptions. Implement the the try-catch blocks for for catching and and handling exceptions. Write programmer-defined exception classes. Distinguish the the checked and and unchecked, or or runtime, exceptions.

3 Introduction to Exception Handling No No matter matter how how well well designed a a program is, is, there there is is always always the the chance chance that that some some kind kind of of error error will will arise arise during during its its execution. A well-designed program should should include include code code to to handle handle errors errors and and other other exceptional conditions when when they they arise. arise. Sometimes the the best best outcome can can be be when when nothing nothing unusual happens However, the the case case where where exceptional things things happen must must also also be be prepared for for Java Java exception handling facilities are are used used when when the the invocation of of a method may may cause cause something exceptional to to occur occur

4 Introduction to Exception Handling Java library software (or (or programmer-defined code) provides a mechanism that signals when something unusual happens This This is is called throwing an an exception In In another place in in the program, the programmer must provide code that deals with the exceptional case This This is is called handling the the exception

5 Definition An exception represents an error condition that can occur during the normal course of of program execution. When an exception occurs, or or is is thrown, the normal sequence of of flow is is terminated. The exception-handling routine is is then executed; we say the thrown exception is is caught.

6 Not Catching Exceptions The avgfirstn() method expects that N > If If N = 0, 0, a divide-by-zero error occurs in in avg/n. /** * Precondition: N > 0 * Postcondition: avgfirstn() equals the average of (1+2+ +N) */ public double avgfirstn(int N) duuble sum = 0; for (int k = 1; k <= N; k++) sum += k; return sum/n; // What if N is 0?? // avgfirstn() Bad Design: Doesn t guard against divide-by-0.

7 class class AgeInputVer1 AgeInputVer1 private private int intage; public public void void setage(string setage(strings) s) age age = Integer.parseInt(s); Integer.parseInt(s); public public int intgetage() return return age; age; Not Catching Exceptions public public class class AgeInputMain1 AgeInputMain1 public public static static void void main( main( String[] String[] args args )) AgeInputVer1 AgeInputVer1 P = new new AgeInputVer1( AgeInputVer1( ); ); P.setAge("nine"); P.setAge("nine"); System.out.println(P.getAge()); Error message for invalid input Exception Exception in in thread thread "main" "main" java.lang.numberformatexception: java.lang.numberformatexception: For For input input string: string: "nine" "nine" at at java.lang.numberformatexception.forinputstring(unknown java.lang.numberformatexception.forinputstring(unknown Source) Source) at at java.lang.integer.parseint(unknown java.lang.integer.parseint(unknown Source) Source) at at java.lang.integer.parseint(unknown java.lang.integer.parseint(unknown Source) Source) at at AgeInputVer1.setAge(AgeInputVer1.java:5) AgeInputVer1.setAge(AgeInputVer1.java:5) at at AgeInputMain1.main(AgeInputMain1.java:8) AgeInputMain1.main(AgeInputMain1.java:8)

8 Not Catching Exceptions class class AgeInputVer1 AgeInputVer1 private private int intage; public public void void setage(string setage(strings) s) age age = Integer.parseInt(s); Integer.parseInt(s); public public int intgetage() return return age; age; public public class class AgeInputMain2 AgeInputMain2 public public static static void void main( main( String[] String[] args args )) AgeInputVer1 AgeInputVer1 P = new new AgeInputVer1( AgeInputVer1( ); ); P.setAge("9"); P.setAge("9"); System.out.println(P.getAge()); 9

9 Java s Exception Hierarchy Unchecked exceptions: belong to a subclass of RuntimeException and are not monitored by the compiler.

10 Some Important Exceptions Class ArithmeticException ArithmeticException ArrayIndexOutOfBounds- ArrayIndexOutOfBounds- FileNotFoundException FileNotFoundException IndexOutOfBoundsException IndexOutOfBoundsException NullPointerException NullPointerException NumberFormatException NumberFormatException StringIndexOutOfBoundsException StringIndexOutOfBoundsException Description Division Division by by zero zero or or some some other other kind kind of of arithmetic arithmetic problem problem An An array array index index is is less less than than zero zero or or Exception Exception greater greater than than or or equal equal to to the the array's array's length length Reference Reference to to a a unfound unfound file file IllegalArgumentException IllegalArgumentException Method Method call call with with improper improper argument argument An An array array or or string string index index out out of of bounds bounds Reference Reference to to an an object object which which has has not not been been instantiated instantiated Use Use of of an an illegal illegal number number format, format, such such as as when when calling calling a a method method A String String index index less less than than zero zero or or greater greater than than or or equal equal to to the the String's String's length length

11 Catching an Exception try catch class class AgeInputVer2 AgeInputVer2 private private int int age age public public void void setage(string setage(string s) s) try try age age = Integer.parseInt(s); catch catch (NumberFormatException e) e) System.out.Println( age System.out.Println( age is is invalid, invalid, Please Please enter enter digits digits only"); only"); public public int int getage() getage() return return age; age; We are catching the number format exception, and the parameter e represents an instance of the NumberFormatException class

12 Catching an Exception To accomplish this repetition, we will put the whole try-catch statement in side a loop: import import java.util.scanner; java.util.scanner; class class AgeInputVer3 AgeInputVer3 private private int int age; age; public public void void setage(string setage(string s) s) String String m =s; =s; Scanner Scanner input input = = new new Scanner(System.in); Scanner(System.in); boolean boolean ok ok = = true; true; while while (ok) (ok) try try age age = = Integer.parseInt(m); Integer.parseInt(m); ok ok = = false; false; catch catch (NumberFormatException (NumberFormatException e) e) System.out.println( age System.out.println( age is is invalid, invalid, Please Please enter enter digits digits only"); only"); m = = input.next(); input.next(); public public int int getage() getage() return return age; age; This This statement statement is is executed executed only only if if no no exception exception is is thrown thrown by by parseint. parseint.

13 try-catch Control Flow

14 The Exception Class: Getting Information There are two methods we can call to get information about the thrown exception: getmessage printstacktrace Simple: only constructor methods.

15 try... The Exception Class: Getting Information catch (NumberFormatException e) We are catching the number format exception, and the parameter e represents an instance of the NumberFormatException class System.out.println(e.getMessage()); System.out.println(e.printStackTrace()); For input string: "nine" java.lang.numberformatexception: For input string: "nine" at java.lang.numberformatexception.forinputstring(unknown Source) at java.lang.integer.parseint(unknown Source) at java.lang.integer.parseint(unknown Source) at AgeInputVer1.setAge(AgeInputVer1.java:11) at AgeInputMain1.main(AgeInputMain1.java:8)

16 try-throw-catch Mechanism throw thrownew new ExceptionClassName(PossiblySomeArguments); When When an an exception exception is is thrown, thrown, the the execution execution of of the the surrounding surrounding try tryblock is is stopped stopped Normally, Normally, the the flow flow of of control control is is transferred transferred to to another another portion portion of of code code known known as as the the catch catchblock The The value value thrown thrown is is the the argument argument to to the the throw throwoperator, operator, and and is is always always an an object object of of some some exception exception class class The The execution execution of of a a throw throwstatement is is called called throwing throwing an an exception exception

17 try-throw-catch Mechanism A throw throw statement statement is is similar similar to to a a method method call: call: throw throw new new ExceptionClassName(SomeString); In In the the above above example, example, the the object object of of class class ExceptionClassName ExceptionClassNameis is created created using using a a string string as as its its argument argument This This object, object, which which is is an an argument argument to to the the throw throw operator, operator, is is the the exception exception object object thrown thrown Instead Instead of of calling calling a a method, method, a a throw throw statement statement calls calls a a catch catch block block

18 try-throw-catch Mechanism When When an an exception exception is is thrown, thrown, the the catch catch block block begins begins execution execution The The catch catch block block has has one one parameter parameter The The exception exception object object thrown thrown is is plugged plugged in in for for the the catch catch block block parameter parameter The The execution execution of of the the catch catch block block is is called called catching catching the the exception, exception, or or handling handling the the exception exception Whenever Whenever an an exception exception is is thrown, thrown, it it should should ultimately ultimately be be handled handled (or (or caught) caught) by by some some catch catch block block

19 try-throw-catch Mechanism When When a try tryblock is is executed, two two things things can can happen: No No exception is is thrown thrown in in the the try try block block The The code code in in the the try tryblock is is executed to to the the end end of of the the block block The The catch catchblock is is skipped The The execution continues with with the the code code placed placed after after the the catch catchblock An An exception is is thrown thrown in in the the try try block block and and caught caught in in the the catch catch block block The The rest rest of of the the code code in in the the try try block block is is skipped Control Control is is transferred to to a following catch catch block block (in (in simple simple cases) cases) The The thrown thrown object object is is plugged in in for for the the catch catch block block parameter The The code code in in the the catch catch block block is is executed The The code code that that follows follows that that catch catch block block is is executed (if (if any) any)

20 public class CalcAverage public double avgfirstn(int N ) double sum = 0; try if (N <=0) throw new Exception("ERROR: Can't average 0 elements"); for (int k = 1; k <= N; k++) sum += k; return sum/n; public class CalcAverage public double avgfirstn(int N ) double sum = 0; try if (N <0) throw new Exception("ERROR: Can't average negative elements"); for (int k = 1; k <= N; k++) sum += k; return sum/n; catch(arithmeticexception e) System.out.println(e.getmessage()); System.out.println( N=Zero is an valid denomiattor, please try again "); catch (Exception e) System.out.println e.getmessage() + Please enter positive integer );

21 Multiple catch Blocks A try tryblock can can potentially throw any any number of of exception values, and and they they can can be be of of differing types In In any any one one execution of of a try tryblock, at at most most one one exception can can be be thrown (since a throw statement ends ends the the execution of of the the try try block) However, different types of of exception values can can be be thrown on on different executions of of the the try tryblock Each Each catch block can can only only catch values of of the the exception class class type type given in in the the catch block heading Different types of of exceptions can can be be caught by by placing more more than than one one catch block after after a try tryblock Any Any number of of catch blocks can can be be included, but but they they must must be be placed in in the the correct order

22 Multiple catch Blocks

23 Multiple catch Control Flow

24 Multiple catch Control Flow: Example import import java.util.*; java.util.*; //InputMismatchException; //InputMismatchException; //import //import java.util.arithmeticexception; java.util.arithmeticexception; public public class class DividbyZero2 DividbyZero2 public public static static void void main main (String (String args[]) args[]) //throws //throws ArithmeticException ArithmeticException Scanner Scanner input input = = new new Scanner(System.in); Scanner(System.in); boolean boolean done=false; done=false; do do try try System.out.print("Please System.out.print("Please enter enter an an integer integer number number : : "); "); int int a a =input.nextint(); =input.nextint(); System.out.print("Please System.out.print("Please enter enter an an integer integer number number : : "); "); int int b b =input.nextint(); =input.nextint(); int int c=a/b; c=a/b; System.out.println("a System.out.println("a ="+ ="+ a a +" +" b= b= "+b+ "+b+ " " amd amd quotient quotient ="+c); ="+c); done=true; done=true; catch (InputMismatchException var1 ) catch (InputMismatchException var1 ) System.out.println("Exception :"+ var1); System.out.println("Exception :"+ var1); System.out.println("please try again: "); System.out.println("please try again: "); catch(arithmeticexception var2) catch(arithmeticexception var2) System.out.println("\nException :"+ var2); System.out.println("\nException :"+ var2); System.out.println("Zero is an valid denomiattor"); System.out.println("Zero is an valid denomiattor"); while(!done); while(!done); Please enter an integer number : car Please enter an integer number : car Exception :java.util.inputmismatchexception Exception :java.util.inputmismatchexception You must enter an integer value, please try again: You must enter an integer value, please try again: Please enter an integer number : 14 Please enter an integer number : 14 Please enter an integer number : 0 Please enter an integer number : 0 Exception :java.lang.arithmeticexception: / by zero Exception :java.lang.arithmeticexception: / by zero Zero is an valid denomiattor, please try again Zero is an valid denomiattor, please try again Please enter an integer number : 7 Please enter an integer number : 7 Please enter an integer number : 3 Please enter an integer number : 3 a =7 b= 3 amd quotient =2 a =7 b= 3 amd quotient =2

25 Pitfall: Catch the More Specific Exception First When catching multiple exceptions, the order of of the catch blocks is is important When an an exception is is thrown in in a try block, the catch blocks are examined in in order The first one that matches the type of of the exception thrown is is the one that is is executed

26 The finally Block

27 try-catch-finally Control Flow

28 try-catch-finally Control Flow If If the the try-catch-finally blocks are are inside a method definition, there are are three possibilities when the the code is is run: run: The Thetry tryblock runs runs to to the the end, end, no no exception is is thrown, thrown, and and the the finally block block is is executed An An exception is is thrown thrown in in the thetry tryblock, caught caught in in one one of of the the catch catchblocks, and and the thefinally block block is is executed An An exception is is thrown thrown in in the thetry tryblock, there there is is no no matching catch catchblock in in the the method, the thefinally block block is is executed, and and then then the the method invocation ends ends and and the the exception object object is is thrown thrown to to the the enclosing method

29 Propagating Exceptions Throwing an Exception in a Method Sometimes it it makes sense to to throw an an exception in in a method, but but not not catch it it in in the the same method Some Some programs that that use use a method should should just just end end if if an an exception is is thrown, thrown, and and other other programs should should do do something else else In In such such cases, cases, the the program using using the the method should should enclose the the method invocation in in a try try block, block, and and catch catch the the exception in in a catch catch block blockthat follows follows In In this this case, case, the the method itself itself would would not not include include try tryand catch catchblocks However, it it would would have have to to include include a throws throwsclause

30 Declaring Exceptions in a throws Clause If If a method can can throw an an exception but but does not not catch it, it, it it must provide a warning This This warning is is called called a throws throwsclause The The process of of including an an exception class class in in a throws throws clause clause is is called called declaring the the exception throws throws AnException //throws clause clause The The following states states that that an an invocation of of amethod could could throw throw AnException public public void void amethod() throws throws AnException

31 Declaring Exceptions in a throws Clause If If a method can throw more than one type of of exception, then separate the exception types by by commas public void void amethod() throws AnException,AnotherException If If a method throws an an exception and does not catch it, it, then the method invocation ends immediately

32 Exception propagation and throws clause Method Method getdepend() may may throw throw a a number number format format exception when when converting a a string string to to an an integer, integer, but but it it does does not not catch catch this this exception. The The call call to to getdepend() occurs occurs in in the the try try block block of of method method main(), main(), so so main() main() handles handles the the exception in in its its catch catch block. block. If If main() main() did did not not have have a a catch catch block block for for number number format format exceptions, the the exception would would be be handled handled by by the the JVM. JVM. // // postcondition: Returns int value of a numeric data string. // postcondition: Throws an exception Returns int if string value is of not a numeric numeric. data string. // Throws an exception if string is not numeric. public public static static int int getdepend() getdepend() throws throws NumberFormatException NumberFormatException String String numstr numstr = = jnputnext(); jnputnext(); return return Integer.parseInt(numStr); Integer.parseInt(numStr); // // postcondition: postcondition: Calls Calls getdepend() getdepend() and and handles handles its its exceptions. exceptions. public public static static void void main(string[] main(string[] args) args) int int children children = = 1; 1; // // problem problem input, input, default default is is 1 1 try try children = getdepend(); children = getdepend(); catch catch (NumberFormatException (NumberFormatException ex) ex) // // Handle Handle number number format format exception. exception. System.out.println("Invalid System.out.println("Invalid integer integer + + ex); ex);

33 Exception Thrower When a method may throw an exception, either directly or or indirectly, we call the method an exception thrower. Every exception thrower must be one of of two types: catcher. propagator.

34 Types of Exception Throwers An exception catcher is is an exception thrower that includes a matching catch block for the thrown exception. An exception propagator does not contain a matching catch block. A method may be a catcher of of one exception and a propagator of of another.

35 Sample Call Sequence Method A calls calls method B, B, Method B calls calls method C, C, Method C calls calls method D. D. Every time a method is executed, the method s name is placed on top of the stack.

36 Sample Call Sequence When an an exception is is thrown, the the system searches down the the stack from from the the top, top, looking for for the the first first matching exception catcher. Method D throws an an exception, but but no nomatching catch block exits exits in in the the method, so so method D is is an an exception propagator. The system then then checks method C. C. C is is also also an an exception propagator. Finally, the the system locates the the matching catch block in in method B, B, and and therefore, method B is is the the catcher for for the the exception thrown by by method D. D. Method A also also includes the the matching catch block, but but it it will will not not be be executed because the the thrown exception is is already caught by by method B and and method B does does not not propagate this this exception. void C() throws Exception. void D() throws Exception.

37 Example Consider Consider the the Fraction Fraction class. class. The The setdenominator setdenominatormethod method of of the the Fraction Fraction class class was was defined defined as as follows: follows: Throwing Throwing an an exception exception is is a a much much better better approach. approach. Here s Here s the the modified modified method method that that throws throws an an IlleglArgumentException when when the the value value of of 00 is is passed passed as as an an argument: argument: public public void voidsetdenominator (int (intd) d) if if (d (d = = 0) 0) System.out.println( Fatal Error ); Error ); System.exit(1); System.exit(1); denominator denominator = d; d; public public void voidsetdenominator (int (intd) d) throws throwsilleglargumentexception if if (d (d = = 0) 0) throw throw new newilleglargumentexception ( Fatal ( Fatal Error ); Error ); denominator denominator = d; d;

38 Programmer-Defined Exception Classes A throw statement can throw an exception object of any exception class Instead of using a predefined class, exception classes can be programmerdefined These can be tailored to carry the precise kinds of information needed in the catch block A different type of exception can be defined to identify each different exceptional situation Every exception class to be defined must be a sub-class of some already defined exception class It can be a sub-class of any exception class in the standard Java libraries, or of any programmer defined exception class Constructors are the most important members to define in an exception class They must behave appropriately with respect to the variables and methods inherited from the base class Often, there are no other members, except those inherited from the base class The following exception class performs these basic tasks only

39 A Programmer-Defined Exception Class

40 Programmer-Defined Exception Class Guidelines Exception classes may be programmer-defined, but every such class must be a derived class of an already existing exception class The class Exception can be used as the base class, unless another class would be more suitable At least two constructors should be defined, sometimes more The exception class should allow for the fact that the method getmessage is inherited

41 Programmer-Defined Exceptions: AgeInputException class AgeInputException extends Exception private static final String DEFAULT_MESSAGE = "Input out of bounds"; private int lowerboun, upperbound, value; public AgeInputException(int low, int high, int input) this(default_message, low, high, input); public AgeInputException(String msg, int low, int high, int input) super(msg); if (low > high) throw new IllegalArgumentException(); lowerbound = low; upperbound = high; value = input; public int lowerbound() return lowerbound; public int upperbound() return upperbound; public int value() return value;

42 Class AgeInputVer5 Uses AgeInputException import java.util.scanner; class AgeInputVer5 private static final String DEFAULT_MESSAGE = "Your age:"; private static final int DEFAULT_LOWER_BOUND = 0; private static final int DEFAULT_UPPER_BOUND = 99; private int lowerbound, upperbound; public AgeInputVer5( ) throws IllegalArgumentException setbounds(default_lower_bound, DEFAULT_UPPER_BOUND); public AgeInputVer5(int low, int high) throws IllegalArgumentException if (low > high) throw new IllegalArgumentException( "Low (" + low + ") was " + "larger than high(" + high + ")"); else setbounds(low, high); public int getage() throws AgeInputException return getage(default_message);

43 public int getage(string prompt) throws AgeInputException Scanner T = new Scanner(System.in); String inputstr; int age; while (true) inputstr = prompt; try age = Integer.parseInt(inputStr); if (age < lowerbound age > upperbound) throw new AgeInputException("Input out of bound ", lowerbound, upperbound, age); return age; //input okay so return the value & exit catch (NumberFormatException e) System.out.println("\n"+ inputstr + " is invalid age."); System.out.print("Please enter age as an integer value : "); prompt = T.next()+T.nextLine(); private void setbounds(int low, int high) lowerbound = low; upperbound = high;

44 Main Using throws public class TestAgeInputUsingThrows public static void main( String[] args ) throws AgeInputException int entrantage=0; AgeInputVer5 input = new AgeInputVer5(25, 50); entrantage = input.getage("thirty"); System.out.println("Input Okay "); Thirty is invalid age. Please enter age as an integer value : fourty fourty is invalid age. Please enter age as an integer value : 40 Input Okay Thirty is invalid age. Please enter age as an integer value : fourty fourty is invalid age. Please enter age as an integer value : 55 Exception in thread "main" AgeInputException: Input out of bound at AgeInputVer5.getAge(AgeInputVersion5.java:42) at TestAgeInputVer5.main(TestAgeInputVer5.java:7)

45 public class Test2AgeInput Main Using try-catch public static void main( String[] args ) int entrantage; try AgeInputVer5 input = new AgeInputVer5(25, 50); entrantage = input.getage("thirty"); System.out.println("Input Okay "); catch (AgeInputException e) System.out.println("Error: " + e.value() + " is entered. It is " + "outside the valid range of [" + e.lowerbound() +", " + e.upperbound() + "]"); Thirty is invalid age. Please enter age as an integer value : fourty fourty is invalid age. Please enter age as an integer value : 40 Input Okay Thirty is invalid age. Please enter age as an integer value : fourty fourty is invalid age. Please enter age as an integer value : 55 Error: 55 is entered. It is outside the valid range of [25, 50]

Chapter 9. Exception Handling. Copyright 2016 Pearson Inc. All rights reserved.

Chapter 9. Exception Handling. Copyright 2016 Pearson Inc. All rights reserved. Chapter 9 Exception Handling Copyright 2016 Pearson Inc. All rights reserved. Last modified 2015-10-02 by C Hoang 9-2 Introduction to Exception Handling Sometimes the best outcome can be when nothing unusual

More information

C16b: Exception Handling

C16b: Exception Handling CISC 3120 C16b: Exception Handling Hui Chen Department of Computer & Information Science CUNY Brooklyn College 3/28/2018 CUNY Brooklyn College 1 Outline Exceptions Catch and handle exceptions (try/catch)

More information

Comp 249 Programming Methodology Chapter 9 Exception Handling

Comp 249 Programming Methodology Chapter 9 Exception Handling Comp 249 Programming Methodology Chapter 9 Exception Handling Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University, Montreal, Canada These slides has been extracted,

More information

Chapter 8. Exception Handling. CS 180 Sunil Prabhakar Department of Computer Science Purdue University

Chapter 8. Exception Handling. CS 180 Sunil Prabhakar Department of Computer Science Purdue University Chapter 8 Exception Handling CS 180 Sunil Prabhakar Department of Computer Science Purdue University Clarifications Auto cast from char to String does not happen. Cast between int and char happens automatically.

More information

BBM 102 Introduction to Programming II Spring Exceptions

BBM 102 Introduction to Programming II Spring Exceptions BBM 102 Introduction to Programming II Spring 2018 Exceptions 1 Today What is an exception? What is exception handling? Keywords of exception handling try catch finally Throwing exceptions throw Custom

More information

More on Exception Handling

More on Exception Handling Chapter 18 More on Exception Handling Lecture slides for: Java Actually: A Comprehensive Primer in Programming Khalid Azim Mughal, Torill Hamre, Rolf W. Rasmussen Cengage Learning, 2008. ISBN: 978-1-844480-933-2

More information

More on Exception Handling

More on Exception Handling Chapter 18 More on Exception Handling Lecture slides for: Java Actually: A Comprehensive Primer in Programming Khalid Azim Mughal, Torill Hamre, Rolf W. Rasmussen Cengage Learning, 2008. ISBN: 978-1-844480-933-2

More information

EXCEPTION HANDLING. // code that may throw an exception } catch (ExceptionType parametername) {

EXCEPTION HANDLING. // code that may throw an exception } catch (ExceptionType parametername) { EXCEPTION HANDLING We do our best to ensure program correctness through a rigorous testing and debugging process, but that is not enough. To ensure reliability, we must anticipate conditions that could

More information

Exception in thread "main" java.lang.arithmeticexception: / by zero at DefaultExceptionHandling.main(DefaultExceptionHandling.

Exception in thread main java.lang.arithmeticexception: / by zero at DefaultExceptionHandling.main(DefaultExceptionHandling. Exceptions 1 Handling exceptions A program will sometimes inadvertently ask the machine to do something which it cannot reasonably do, such as dividing by zero, or attempting to access a non-existent array

More information

BBM 102 Introduction to Programming II Spring 2017

BBM 102 Introduction to Programming II Spring 2017 BBM 102 Introduction to Programming II Spring 2017 Exceptions Instructors: Ayça Tarhan, Fuat Akal, Gönenç Ercan, Vahid Garousi Today What is an exception? What is exception handling? Keywords of exception

More information

Chapter 12 Exception Handling

Chapter 12 Exception Handling Chapter 12 Exception Handling 1 Motivations Goal: Robust code. When a program runs into a runtime error, the program terminates abnormally. How can you handle the runtime error so that the program can

More information

Exceptions. References. Exceptions. Exceptional Conditions. CSE 413, Autumn 2005 Programming Languages

Exceptions. References. Exceptions. Exceptional Conditions. CSE 413, Autumn 2005 Programming Languages References Exceptions "Handling Errors with Exceptions", Java tutorial http://java.sun.com/docs/books/tutorial/essential/exceptions/index.html CSE 413, Autumn 2005 Programming Languages http://www.cs.washington.edu/education/courses/413/05au/

More information

A Third Look At Java. Chapter Seventeen Modern Programming Languages, 2nd ed. 1

A Third Look At Java. Chapter Seventeen Modern Programming Languages, 2nd ed. 1 A Third Look At Java Chapter Seventeen Modern Programming Languages, 2nd ed. 1 A Little Demo public class Test { public static void main(string[] args) { int i = Integer.parseInt(args[0]); int j = Integer.parseInt(args[1]);

More information

COE318 Lecture Notes Week 10 (Nov 7, 2011)

COE318 Lecture Notes Week 10 (Nov 7, 2011) COE318 Software Systems Lecture Notes: Week 10 1 of 5 COE318 Lecture Notes Week 10 (Nov 7, 2011) Topics More about exceptions References Head First Java: Chapter 11 (Risky Behavior) The Java Tutorial:

More information

CSC System Development with Java. Exception Handling. Department of Statistics and Computer Science. Budditha Hettige

CSC System Development with Java. Exception Handling. Department of Statistics and Computer Science. Budditha Hettige CSC 308 2.0 System Development with Java Exception Handling Department of Statistics and Computer Science 1 2 Errors Errors can be categorized as several ways; Syntax Errors Logical Errors Runtime Errors

More information

Full file at Chapter 2 - Inheritance and Exception Handling

Full file at   Chapter 2 - Inheritance and Exception Handling Chapter 2 - Inheritance and Exception Handling TRUE/FALSE 1. The superclass inherits all its properties from the subclass. ANS: F PTS: 1 REF: 76 2. Private members of a superclass can be accessed by a

More information

ITI Introduction to Computing II

ITI Introduction to Computing II ITI 1121. Introduction to Computing II Marcel Turcotte School of Electrical Engineering and Computer Science Version of February 23, 2013 Abstract Handling errors Declaring, creating and handling exceptions

More information

Exceptions. CSE 142, Summer 2002 Computer Programming 1.

Exceptions. CSE 142, Summer 2002 Computer Programming 1. Exceptions CSE 142, Summer 2002 Computer Programming 1 http://www.cs.washington.edu/education/courses/142/02su/ 12-Aug-2002 cse142-19-exceptions 2002 University of Washington 1 Reading Readings and References»

More information

Exceptions. Readings and References. Exceptions. Exceptional Conditions. Reading. CSE 142, Summer 2002 Computer Programming 1.

Exceptions. Readings and References. Exceptions. Exceptional Conditions. Reading. CSE 142, Summer 2002 Computer Programming 1. Readings and References Exceptions CSE 142, Summer 2002 Computer Programming 1 http://www.cs.washington.edu/education/courses/142/02su/ Reading» Chapter 18, An Introduction to Programming and Object Oriented

More information

Exception-Handling Overview

Exception-Handling Overview م.عبد الغني أبوجبل Exception Handling No matter how good a programmer you are, you cannot control everything. Things can go wrong. Very wrong. When you write a risky method, you need code to handle the

More information

ITI Introduction to Computing II

ITI Introduction to Computing II ITI 1121. Introduction to Computing II Marcel Turcotte School of Electrical Engineering and Computer Science Version of February 23, 2013 Abstract Handling errors Declaring, creating and handling exceptions

More information

CS115. Chapter 17 Exception Handling. Prof. Joe X. Zhou Department of Computer Science. To know what is exception and what is exception handling

CS115. Chapter 17 Exception Handling. Prof. Joe X. Zhou Department of Computer Science. To know what is exception and what is exception handling CS115 Pi Principles i of fcomputer Science Chapter 17 Exception Handling Prof. Joe X. Zhou Department of Computer Science CS115 ExceptionHandling.1 Objectives in Exception Handling To know what is exception

More information

Programming II (CS300)

Programming II (CS300) 1 Programming II (CS300) Chapter 04: Exception Handling MOUNA KACEM mouna@cs.wisc.edu Fall 2018 Creating Classes 2 Introduction Exception Handling Common Exceptions Exceptions with Methods Assertions and

More information

Programming II (CS300)

Programming II (CS300) 1 Programming II (CS300) Chapter 04: Exception Handling MOUNA KACEM mouna@cs.wisc.edu Spring 2018 Creating Classes 2 Introduction Exception Handling Common Exceptions Exceptions with Methods Assertions

More information

Topic 6: Exceptions. Exceptions are a Java mechanism for dealing with errors & unusual situations

Topic 6: Exceptions. Exceptions are a Java mechanism for dealing with errors & unusual situations Topic 6: Exceptions Exceptions are a Java mechanism for dealing with errors & unusual situations Goals: learn how to... think about different responses to errors write code that catches exceptions write

More information

I/O Streams. program. Standard I/O. File I/O: Setting up streams from files. program. File I/O and Exceptions. Dr. Papalaskari 1

I/O Streams. program. Standard I/O. File I/O: Setting up streams from files. program. File I/O and Exceptions. Dr. Papalaskari 1 File I/O and Exceptions CSC 1051 Data Structures and Algorithms I I/O Streams Programs read information from input streams and write information to output streams Dr. Mary-Angela Papalaskari Department

More information

I/O Streams. program. Standard I/O. File I/O: Setting up streams from files. program. File I/O and Exceptions. Dr. Papalaskari 1

I/O Streams. program. Standard I/O. File I/O: Setting up streams from files. program. File I/O and Exceptions. Dr. Papalaskari 1 File I/O and Exceptions CSC 1051 Data Structures and Algorithms I I/O Streams Programs read information from input streams and write information to output streams Dr. Mary-Angela Papalaskari Department

More information

CS1020 Data Structures and Algorithms I Lecture Note #8. Exceptions Handling exceptional events

CS1020 Data Structures and Algorithms I Lecture Note #8. Exceptions Handling exceptional events CS1020 Data Structures and Algorithms I Lecture Note #8 Exceptions Handling exceptional events Objectives Understand how to use the mechanism of exceptions to handle errors or exceptional events that occur

More information

What are Exceptions?

What are Exceptions? Exception Handling What are Exceptions? The traditional approach Exception handing in Java Standard exceptions in Java Multiple catch handlers Catching multiple exceptions finally block Checked vs unchecked

More information

CSCI 261 Computer Science II

CSCI 261 Computer Science II CSCI 261 Computer Science II Department of Mathematics and Computer Science Lecture 2 Exception Handling New Topic: Exceptions in Java You should now be familiar with: Advanced object-oriented design -

More information

Exception Handling. Sometimes when the computer tries to execute a statement something goes wrong:

Exception Handling. Sometimes when the computer tries to execute a statement something goes wrong: Exception Handling Run-time errors The exception concept Throwing exceptions Handling exceptions Declaring exceptions Creating your own exception Ariel Shamir 1 Run-time Errors Sometimes when the computer

More information

Exception Handling. Run-time Errors. Methods Failure. Sometimes when the computer tries to execute a statement something goes wrong:

Exception Handling. Run-time Errors. Methods Failure. Sometimes when the computer tries to execute a statement something goes wrong: Exception Handling Run-time errors The exception concept Throwing exceptions Handling exceptions Declaring exceptions Creating your own exception 22 November 2007 Ariel Shamir 1 Run-time Errors Sometimes

More information

About This Lecture. Outline. Handling Unusual Situations. Reacting to errors. Exceptions

About This Lecture. Outline. Handling Unusual Situations. Reacting to errors. Exceptions Exceptions Revised 24-Jan-05 CMPUT 115 - Lecture 4 Department of Computing Science University of Alberta About This Lecture In this lecture we will learn how to use Java Exceptions to handle unusual program

More information

Exceptions - Example. Exceptions - Example

Exceptions - Example. Exceptions - Example - Example //precondition: x >= 0 public void sqrt(double x) double root; if (x < 0.0) //What to do? else //compute the square root of x return root; 1 - Example //precondition: x >= 0 public void sqrt(double

More information

Assoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Assoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved. Assoc. Prof. Marenglen Biba Exception handling Exception an indication of a problem that occurs during a program s execution. The name exception implies that the problem occurs infrequently. With exception

More information

Chapter 15. Exception Handling. Chapter Goals. Error Handling. Error Handling. Throwing Exceptions. Throwing Exceptions

Chapter 15. Exception Handling. Chapter Goals. Error Handling. Error Handling. Throwing Exceptions. Throwing Exceptions Chapter 15 Exception Handling Chapter Goals To learn how to throw exceptions To be able to design your own exception classes To understand the difference between checked and unchecked exceptions To learn

More information

CMSC 202. Exceptions

CMSC 202. Exceptions CMSC 202 Exceptions Error Handling In the ideal world, all errors would occur when your code is compiled. That won t happen. Errors which occur when your code is running must be handled by some mechanism

More information

Administration. Exceptions. Leftovers. Agenda. When Things Go Wrong. Handling Errors. CS 99 Summer 2000 Michael Clarkson Lecture 11

Administration. Exceptions. Leftovers. Agenda. When Things Go Wrong. Handling Errors. CS 99 Summer 2000 Michael Clarkson Lecture 11 Administration Exceptions CS 99 Summer 2000 Michael Clarkson Lecture 11 Lab 10 due tomorrow No lab tomorrow Work on final projects Remaining office hours Rick: today 2-3 Michael: Thursday 10-noon, Monday

More information

COSC 123 Computer Creativity. I/O Streams and Exceptions. Dr. Ramon Lawrence University of British Columbia Okanagan

COSC 123 Computer Creativity. I/O Streams and Exceptions. Dr. Ramon Lawrence University of British Columbia Okanagan COSC 123 Computer Creativity I/O Streams and Exceptions Dr. Ramon Lawrence University of British Columbia Okanagan ramon.lawrence@ubc.ca Objectives Explain the purpose of exceptions. Examine the try-catch-finally

More information

EXCEPTIONS. Fundamentals of Computer Science I

EXCEPTIONS. Fundamentals of Computer Science I EXCEPTIONS Exception in thread "main" java.lang.numberformatexception: For input string: "3.5" at java.lang.numberformatexception.forinputstring(numberformatexception.java:48) at java.lang.integer.parseint(integer.java:458)

More information

More Control Structures

More Control Structures Chapter 8 More Control Structures 1 8.1 Exceptions When a Java program performs an illegal operation, an exception happens. If a program has no special provisions for dealing with exceptions, it will behave

More information

Fundamentals of Object Oriented Programming

Fundamentals of Object Oriented Programming INDIAN INSTITUTE OF TECHNOLOGY ROORKEE Fundamentals of Object Oriented Programming CSN- 103 Dr. R. Balasubramanian Associate Professor Department of Computer Science and Engineering Indian Institute of

More information

Introduction. Exceptions: An OO Way for Handling Errors. Common Runtime Errors. Error Handling. Without Error Handling Example 1

Introduction. Exceptions: An OO Way for Handling Errors. Common Runtime Errors. Error Handling. Without Error Handling Example 1 Exceptions: An OO Way for Handling Errors Introduction Rarely does a program runs successfully at its very first attempt. It is common to make mistakes while developing as well as typing a program. Such

More information

Data Structures. 02 Exception Handling

Data Structures. 02 Exception Handling David Drohan Data Structures 02 Exception Handling JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN 0132162709 2012 Pearson Education, Inc., Upper Saddle River, NJ.

More information

ECE 122. Engineering Problem Solving with Java

ECE 122. Engineering Problem Solving with Java ECE 122 Engineering Problem Solving with Java Lecture 24 Exceptions Overview Problem: Can we detect run-time errors and take corrective action? Try-catch Test for a variety of different program situations

More information

Chapter 13 Exception Handling

Chapter 13 Exception Handling Chapter 13 Exception Handling 1 Motivations When a program runs into a runtime error, the program terminates abnormally. How can you handle the runtime error so that the program can continue to run or

More information

COMP200 EXCEPTIONS. OOP using Java, based on slides by Shayan Javed

COMP200 EXCEPTIONS. OOP using Java, based on slides by Shayan Javed 1 1 COMP200 EXCEPTIONS OOP using Java, based on slides by Shayan Javed Exception Handling 2 3 Errors Syntax Errors Logic Errors Runtime Errors 4 Syntax Errors Arise because language rules weren t followed.

More information

Midterm Examination (MTA)

Midterm Examination (MTA) M105: Introduction to Programming with Java Midterm Examination (MTA) Spring 2013 / 2014 Question One: [6 marks] Choose the correct answer and write it on the external answer booklet. 1. Compilers and

More information

File I/O and Exceptions

File I/O and Exceptions File I/O and Exceptions CSC 1051 Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website: www.csc.villanova.edu/~map/1051/ Some

More information

I/O Streams. program. Standard I/O. File I/O: Setting up streams from files. program. File I/O and Exceptions. Dr. Papalaskari 1

I/O Streams. program. Standard I/O. File I/O: Setting up streams from files. program. File I/O and Exceptions. Dr. Papalaskari 1 File I/O and Exceptions CSC 1051 Data Structures and Algorithms I I/O Streams Programs read information from input streams and write information to output streams Dr. Mary-Angela Papalaskari Department

More information

CS159. Nathan Sprague

CS159. Nathan Sprague CS159 Nathan Sprague What s wrong with the following code? 1 /* ************************************************** 2 * Return the mean, or -1 if the array has length 0. 3 ***************************************************

More information

Typecasts and Dynamic Dispatch. Dynamic dispatch

Typecasts and Dynamic Dispatch. Dynamic dispatch Typecasts and Dynamic Dispatch Abstract Data Type (ADT) Abstraction Program Robustness Exceptions D0010E Lecture 8 Template Design Pattern Review: I/O Typecasts change the type of expressions as interpreted

More information

Question one package excep;

Question one package excep; Question one package excep; public class student1 private int age; public void setage(string s) age = Integer.parseInt( s); public int getage() return age; package excep; public class studentmain public

More information

CS 3 Introduction to Software Engineering. 3: Exceptions

CS 3 Introduction to Software Engineering. 3: Exceptions CS 3 Introduction to Software Engineering 3: Exceptions Questions? 2 Objectives Last Time: Procedural Abstraction This Time: Procedural Abstraction II Focus on Exceptions. Starting Next Time: Data Abstraction

More information

Chapter 11 Handling Exceptions and Events. Chapter Objectives

Chapter 11 Handling Exceptions and Events. Chapter Objectives Chapter 11 Handling Exceptions and Events Chapter Objectives Learn what an exception is See how a try/catch block is used to handle exceptions Become aware of the hierarchy of exception classes Learn about

More information

What is the purpose of exceptions and exception handling? Vocabulary: throw/raise and catch/handle Exception propagation Java checked and unchecked

What is the purpose of exceptions and exception handling? Vocabulary: throw/raise and catch/handle Exception propagation Java checked and unchecked What is the purpose of exceptions and exception handling? Vocabulary: throw/raise and catch/handle Exception propagation Java checked and unchecked exceptions Java try statement Final wishes Java try-resource

More information

Introduction to Computation and Problem Solving. Class 25: Error Handling in Java. Prof. Steven R. Lerman and Dr. V. Judson Harward.

Introduction to Computation and Problem Solving. Class 25: Error Handling in Java. Prof. Steven R. Lerman and Dr. V. Judson Harward. Introduction to Computation and Problem Solving Class 25: Error Handling in Java Prof. Steven R. Lerman and Dr. V. Judson Harward Goals In this session we are going to explore better and worse ways to

More information

Le L c e t c ur u e e 5 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Exception Handling

Le L c e t c ur u e e 5 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Exception Handling Course Name: Advanced Java Lecture 5 Topics to be covered Exception Handling Exception HandlingHandlingIntroduction An exception is an abnormal condition that arises in a code sequence at run time A Java

More information

CSC 1214: Object-Oriented Programming

CSC 1214: Object-Oriented Programming CSC 1214: Object-Oriented Programming J. Kizito Makerere University e-mail: jkizito@cis.mak.ac.ug www: http://serval.ug/~jona materials: http://serval.ug/~jona/materials/csc1214 e-learning environment:

More information

COMP1008 Exceptions. Runtime Error

COMP1008 Exceptions. Runtime Error Runtime Error COMP1008 Exceptions Unexpected error that terminates a program. Undesirable Not detectable by compiler. Caused by: Errors in the program logic. Unexpected failure of services E.g., file server

More information

Java Errors and Exceptions. Because Murphy s Law never fails

Java Errors and Exceptions. Because Murphy s Law never fails Java Errors and Exceptions Because Murphy s Law never fails 1 Java is the most distressing thing to hit computing since MS-DOS. Alan Kay 2 Corresponding Book Sections Pearson Custom Computer Science: Chapter

More information

Reminder. Topics CSE What Are Exceptions?! Lecture 11 Exception Handling

Reminder. Topics CSE What Are Exceptions?! Lecture 11 Exception Handling Reminder CSE 1720 Lecture 11 Exception Handling Midterm Exam" Thursday, Feb 16, 10-11:30" CLH J Curtis Lecture Hall, Room J! will cover all material up to and including Tues Feb 14th! Tues, Feb 7 topic:

More information

CS112 Lecture: Exceptions. Objectives: 1. Introduce the concepts of program robustness and reliability 2. Introduce exceptions

CS112 Lecture: Exceptions. Objectives: 1. Introduce the concepts of program robustness and reliability 2. Introduce exceptions CS112 Lecture: Exceptions Objectives: 1. Introduce the concepts of program robustness and reliability 2. Introduce exceptions Materials: 1. Online Java documentation to project 2. ExceptionDemo.java to

More information

Object Oriented Programming Exception Handling

Object Oriented Programming Exception Handling Object Oriented Programming Exception Handling Budditha Hettige Department of Computer Science Programming Errors Types Syntax Errors Logical Errors Runtime Errors Syntax Errors Error in the syntax of

More information

Exceptions. CSC207 Winter 2017

Exceptions. CSC207 Winter 2017 Exceptions CSC207 Winter 2017 What are exceptions? In Java, an exception is an object. Exceptions represent exceptional conditions: unusual, strange, disturbing. These conditions deserve exceptional treatment:

More information

CS112 Lecture: Exceptions and Assertions

CS112 Lecture: Exceptions and Assertions Objectives: CS112 Lecture: Exceptions and Assertions 1. Introduce the concepts of program robustness and reliability 2. Introduce exceptions 3. Introduce assertions Materials: 1. Online Java documentation

More information

Chapter 10. Exception Handling. Java Actually: A Comprehensive Primer in Programming

Chapter 10. Exception Handling. Java Actually: A Comprehensive Primer in Programming Chapter 10 Exception Handling Lecture slides for: Java Actually: A Comprehensive Primer in Programming Khalid Azim Mughal, Torill Hamre, Rolf W. Rasmussen Cengage Learning, 2008. ISBN: 978-1-844480-933-2

More information

Java Programming: from the Beginning. Chapter 8 More Control Structures. CSc 2310: Principle of Programming g( (Java) Spring 2013

Java Programming: from the Beginning. Chapter 8 More Control Structures. CSc 2310: Principle of Programming g( (Java) Spring 2013 CSc 2310: Principle of Programming g( (Java) Spring 2013 Java Programming: from the Beginning Chapter 8 More Control Structures 1 Copyright 2000 W. W. Norton & Company. All rights reserved. 81 8.1 Exceptions

More information

C17: File I/O and Exception Handling

C17: File I/O and Exception Handling CISC 3120 C17: File I/O and Exception Handling Hui Chen Department of Computer & Information Science CUNY Brooklyn College 10/24/2017 CUNY Brooklyn College 1 Outline Recap and issues Exception Handling

More information

Exception Handling. Chapter 11. Outline. Example: The Quotient app What Are Exceptions? Java By Abstraction Chapter 11

Exception Handling. Chapter 11. Outline. Example: The Quotient app What Are Exceptions? Java By Abstraction Chapter 11 Outline Chapter 11 Exception Handling 11.1 What are Exceptions? 11.1.1 Exception Handling 11.1.2 The Delegation Model 11.2 Java's Exception Constructs 11.2.1 The Basic -catch Construct 11.2.2 Handling

More information

The University of Melbourne Department of Computer Science and Software Engineering Software Design Semester 2, 2003

The University of Melbourne Department of Computer Science and Software Engineering Software Design Semester 2, 2003 The University of Melbourne Department of Computer Science and Software Engineering 433-254 Software Design Semester 2, 2003 Answers for Tutorial 7 Week 8 1. What are exceptions and how are they handled

More information

Exceptions and Error Handling

Exceptions and Error Handling Exceptions and Error Handling Michael Brockway January 16, 2015 Some causes of failures Incorrect implementation does not meet the specification. Inappropriate object request invalid index. Inconsistent

More information

COMP-202. Exceptions. COMP Exceptions, 2011 Jörg Kienzle and others

COMP-202. Exceptions. COMP Exceptions, 2011 Jörg Kienzle and others COMP-202 Exceptions Lecture Outline Exceptions Exception Handling The try-catch statement The try-catch-finally statement Exception propagation Checked Exceptions 2 Exceptions An exception is an object

More information

Introduction to Software Design

Introduction to Software Design CSI 1102 1 Abdulmotaleb El Saddik University of Ottawa School of Information Technology and Engineering (SITE) Multimedia Communications Research Laboratory (MCRLab) Distributed Collaborative Virtual Environments

More information

Exceptions Handeling

Exceptions Handeling Exceptions Handeling Dr. Ahmed ElShafee Dr. Ahmed ElShafee, Fundamentals of Programming II, ١ Agenda 1. * 2. * 3. * ٢ Dr. Ahmed ElShafee, Fundamentals of Programming II, Introduction During the execution

More information

Chapter 12 Exception Handling and Text IO. Liang, Introduction to Java Programming, Tenth Edition, Global Edition. Pearson Education Limited

Chapter 12 Exception Handling and Text IO. Liang, Introduction to Java Programming, Tenth Edition, Global Edition. Pearson Education Limited Chapter 12 Exception Handling and Text IO Liang, Introduction to Java Programming, Tenth Edition, Global Edition. Pearson Education Limited 2015 1 Motivations When a program runs into a runtime error,

More information

Intermediate Programming. Runtime Errors

Intermediate Programming. Runtime Errors Intermediate Programming Lecture 8 Exception Handling Runtime Errors Sometimes programs are stopped because their errors are so severe that they cannot recover from them. These are called fatal errors

More information

EXCEPTION HANDLING. Summer 2018

EXCEPTION HANDLING. Summer 2018 EXCEPTION HANDLING Summer 2018 EXCEPTIONS An exception is an object that represents an error or exceptional event that has occurred. These events are usually errors that occur because the run-time environment

More information

COMP-202 Unit 9: Exceptions

COMP-202 Unit 9: Exceptions COMP-202 Unit 9: Exceptions Announcements - Assignment 4: due Monday April 16th - Assignment 4: tutorial - Final exam tutorial next week 2 Exceptions An exception is an object that describes an unusual

More information

Std 12 Lesson-10 Exception Handling in Java ( 1

Std 12 Lesson-10 Exception Handling in Java (  1 Ch-10 : Exception Handling in Java 1) It is usually understood that a compiled program is error free and will always successfully. (a) complete (b) execute (c) perform (d) accomplish 2) In few cases a

More information

Exception Handling Introduction. Error-Prevention Tip 13.1 OBJECTIVES

Exception Handling Introduction. Error-Prevention Tip 13.1 OBJECTIVES 1 2 13 Exception Handling It is common sense to take a method and try it. If it fails, admit it frankly and try another. But above all, try something. Franklin Delano Roosevelt O throw away the worser

More information

Lecture 19 Programming Exceptions CSE11 Fall 2013

Lecture 19 Programming Exceptions CSE11 Fall 2013 Lecture 19 Programming Exceptions CSE11 Fall 2013 When Things go Wrong We've seen a number of run time errors Array Index out of Bounds e.g., Exception in thread "main" java.lang.arrayindexoutofboundsexception:

More information

Exceptions, try - catch - finally, throws keyword. JAVA Standard Edition

Exceptions, try - catch - finally, throws keyword. JAVA Standard Edition Exceptions, try - catch - finally, throws keyword JAVA Standard Edition Java - Exceptions An exception (or exceptional event) is a problem that arises during the execution of a program. When an Exception

More information

For more details on SUN Certifications, visit

For more details on SUN Certifications, visit Exception Handling For more details on SUN Certifications, visit http://sunjavasnips.blogspot.com/ Q: 01 Given: 11. public static void parse(string str) { 12. try { 13. float f = Float.parseFloat(str);

More information

Exception Handling in Java. An Exception is a compile time / runtime error that breaks off the

Exception Handling in Java. An Exception is a compile time / runtime error that breaks off the Description Exception Handling in Java An Exception is a compile time / runtime error that breaks off the program s execution flow. These exceptions are accompanied with a system generated error message.

More information

17. Handling Runtime Problems

17. Handling Runtime Problems Handling Runtime Problems 17.1 17. Handling Runtime Problems What are exceptions? Using the try structure Creating your own exceptions Methods that throw exceptions SKILLBUILDERS Handling Runtime Problems

More information

Input-Output and Exception Handling

Input-Output and Exception Handling Software and Programming I Input-Output and Exception Handling Roman Kontchakov / Carsten Fuhs Birkbeck, University of London Outline Reading and writing text files Exceptions The try block catch and finally

More information

CMSC131. Exceptions and Exception Handling. When things go "wrong" in a program, what should happen.

CMSC131. Exceptions and Exception Handling. When things go wrong in a program, what should happen. CMSC131 Exceptions and Exception Handling When things go "wrong" in a program, what should happen. Go forward as if nothing is wrong? Try to handle what's going wrong? Pretend nothing bad happened? Crash

More information

Java Exception. Wang Yang

Java Exception. Wang Yang Java Exception Wang Yang wyang@njnet.edu.cn Last Chapter Review A Notion of Exception Java Exceptions Exception Handling How to Use Exception User-defined Exceptions Last Chapter Review Last Chapter Review

More information

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 19: NOV. 15TH INSTRUCTOR: JIAYIN WANG

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 19: NOV. 15TH INSTRUCTOR: JIAYIN WANG CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 19: NOV. 15TH INSTRUCTOR: JIAYIN WANG 1 Notice Assignment Class Exercise 19 is assigned Homework 8 is assigned Both Homework 8 and Exercise 19 are

More information

CSC207H: Software Design. Exceptions. CSC207 Winter 2018

CSC207H: Software Design. Exceptions. CSC207 Winter 2018 Exceptions CSC207 Winter 2018 1 What are exceptions? Exceptions represent exceptional conditions: unusual, strange, disturbing. These conditions deserve exceptional treatment: not the usual go-tothe-next-step,

More information

Exception Handling. General idea Checked vs. unchecked exceptions Semantics of... Example from text: DataAnalyzer.

Exception Handling. General idea Checked vs. unchecked exceptions Semantics of... Example from text: DataAnalyzer. Exception Handling General idea Checked vs. unchecked exceptions Semantics of throws try-catch Example from text: DataAnalyzer Exceptions [Bono] 1 Announcements Lab this week is based on the textbook example

More information

Correctness and Robustness

Correctness and Robustness Correctness and Robustness 188230 Advanced Computer Programming Asst. Prof. Dr. Kanda Runapongsa Saikaew (krunapon@kku.ac.th) Department of Computer Engineering Khon Kaen University 1 Agenda Introduction

More information

Exceptions and Libraries

Exceptions and Libraries Exceptions and Libraries RS 9.3, 6.4 Some slides created by Marty Stepp http://www.cs.washington.edu/143/ Edited by Sarah Heckman 1 Exceptions exception: An object representing an error or unusual condition.

More information

Exceptions and I/O: sections Introductory Programming. Errors in programs. Exceptions

Exceptions and I/O: sections Introductory Programming. Errors in programs. Exceptions Introductory Programming Exceptions and I/O: sections 80 83 Anne Haxthausen a IMM, DTU 1 Exceptions (section 80) 2 Input and output (I/O) (sections 81-83) a Parts of this material are inspired by/originate

More information

Introductory Programming Exceptions and I/O: sections

Introductory Programming Exceptions and I/O: sections Introductory Programming Exceptions and I/O: sections 80 83 Anne Haxthausen a IMM, DTU 1 Exceptions (section 80) 2 Input and output (I/O) (sections 81-83) a Parts of this material are inspired by/originate

More information

Contents. I Introductory Examples. Topic 06 -Exception Handling

Contents. I Introductory Examples. Topic 06 -Exception Handling Contents Topic 06 - Handling I. Introductory Examples (Example 1-5) II. Handling Basic Idea III. Hierarchy IV. The Try-throw-catch Mechanism V. Define our own classes (Example 6) VI. Pitfall: Catch the

More information

Exceptions Chapter 10. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Exceptions Chapter 10. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013 Exceptions Chapter 10 Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013 2 Scope Exceptions: The purpose of exceptions Exception messages The call stack trace The try-catch statement Exception

More information

Recitation 3. 2D Arrays, Exceptions

Recitation 3. 2D Arrays, Exceptions Recitation 3 2D Arrays, Exceptions 2D arrays 2D Arrays Many applications have multidimensional structures: Matrix operations Collection of lists Board games (Chess, Checkers) Images (rows and columns of

More information

COMP-202 Unit 9: Exceptions

COMP-202 Unit 9: Exceptions COMP-202 Unit 9: Exceptions Course Evaluations Please do these. -Fast to do -Used to improve course for future. (Winter 2011 had 6 assignments reduced to 4 based on feedback!) 2 Avoiding errors So far,

More information