13: Error Handling with Exceptions. The basic philosophy of Java is that "badly formed code will not be run."

Size: px
Start display at page:

Download "13: Error Handling with Exceptions. The basic philosophy of Java is that "badly formed code will not be run.""

Transcription

1 13: Error Handling with Exceptions The basic philosophy of Java is that "badly formed code will not be run." 1

2 Error Handling in Java C++/Java: Badly-formed code will not compile. Java: Badly-formed code, if compiled, will not run. Not all errors can be caught at compile time. Run-time error handling is integrated into the core of the language and enforced by the compiler. The standard libraries require the handling of exceptional conditions. 2

3 Sources of Problems Program logic. Errors like exceeding array bounds and division by zero can be prevented by the programmer. Environmental conditions. Loss of a network connection or a full disk can be anticipated but not prevented. 3

4 Exceptions An exception is an object that signals an error condition and provides information about the error. When an exception is generated, control is passed up the call stack until a specific handler is found. Multiple handlers for different exceptions may be provided at multiple levels. In Java, many exceptions cannot be ignored. This is enforced by the compiler. 4

5 Basic Exceptions An exceptional condition is a problem that prevents the continuation of the current method or scope. To indicate such a condition, one throws an exception object: if (t == null) throw new NullPointerException(); or If (t == null) throw new NullPointerException("t = null"); 5

6 The Exception Class Hierarchy Throwable Error Exception Runtime Exception Checked Exceptions Unchecked Exceptions 6

7 Throwable Methods public class Throwable implements Serializable { public Throwable(); public Throwable(String message); public Throwable(Throwable cause); public Throwable(String message, Throwable cause); public Throwable getcause(); public String getlocalizedmessage(); public String getmessage(); public StackTraceElement[] getstacktrace(); public void setstacktrace(stacktraceelement[] stacktrace); public Throwable fillinstacktrace(); public Throwable initcause(throwable cause); public void printstacktrace(); public void printstacktrace(java.io.printstream s); public void printstacktrace(java.io.printwriter s); public String tostring(); 7

8 Exception & RuntimeException Methods public class Exception extends Throwable { public Exception(); public Exception(Throwable cause); public Exception(String message); public Exception(String message, Throwable cause); public class RuntimeException extends Exception { public RuntimeException(); public RuntimeException(Throwable cause); public RuntimeException(String message); public RuntimeException(String message, Throwable cause); 8

9 Catching Exceptions A thrown exception will cause immediate transfer from a try block to an appropriate catch clause. /* Code that might generate exceptions */ catch (Type1 e1) { /* Handle exceptions of Type1 */ catch (Type2 e2) { /* Handle exceptions of Type2 */ catch (Type3 e3) { /* Handle exceptions of Type3 */ finally { /* Execute code that will always run */ 9

10 The Exception Specification Any exception thrown by a method (except for runtime exceptions) must be declared in a throws clause. This is enforced by the compiler. All checked exceptions will be caught somewhere. 10

11 Creating an Exception Throwing MyException from f() MyException at FullConstructors.f(FullConstructors.java:10) at FullConstructors.main(FullConstructors.java:16) Throwing MyException from g() MyException: Originated in g() at FullConstructors.g(FullConstructors.java:13) at FullConstructors.main(FullConstructors.java:20) 11

12 Getting More Creative class MyException2 extends Exception { private int x; public MyException2() { public MyException2(String msg) { super(msg); public MyException2(String msg, int x) { super(msg); this.x = x; public int val() { return x; public String getmessage() { return "Detail Message: " + x + " " + super.getmessage(); 12

13 Testing the Class public class ExtraFeatures { public static void f() throws MyException2 { print("throwing MyException2 from f()"); throw new MyException2(); public static void g() throws MyException2 { print("throwing MyException2 from g()"); throw new MyException2("Originated in g()"); public static void h() throws MyException2 { print("throwing MyException2 from h()"); throw new MyException2("Originated in h()", 47); public static void main(string[] args) { f(); catch (MyException2 e) { e.printstacktrace(system.out); g(); catch (MyException2 e) { e.printstacktrace(system.out); Throwing MyException2 from f() MyException2: Detail Message: 0 null at ExtraFeatures.f(ExtraFeatures.java:22) at ExtraFeatures.main(ExtraFeatures.java:34) Throwing MyException2 from g() MyException2: Detail Message: 0 Originated in g() at ExtraFeatures.g(ExtraFeatures.java:26) at ExtraFeatures.main(ExtraFeatures.java:39) Throwing MyException2 from h() h(); MyException2: Detail Message: 47 Originated in h() catch (MyException2 e) { at ExtraFeatures.h(ExtraFeatures.java:30) e.printstacktrace(system.out); at ExtraFeatures.main(ExtraFeatures.java:44) System.out.println("e.val() e.val() = " + = e.val()); 47 13

14 Rethrowing A caught exception may be partially handled and thrown again: catch(exception e) System.err.println("An exception was thrown."); throw e; The rethrown exception goes to the next higher context. All of its contained information is preserved. 14

15 Installing a New Stack Trace public class Rethrowing { public static void f() throws Exception { System.out.println("originating the exception in f()"); throw new Exception("thrown from f()"); public static void g() throws Exception { f(); catch (Exception e) { originating the exception in f() System.out.println("Inside g(),e.printstacktrace()"); Inside g(),e.printstacktrace() e.printstacktrace(system.out); java.lang.exception: thrown from f() throw e; public static void h() throws Exception { f(); catch (Exception e) { System.out.println("Inside h(),e.printstacktrace()"); e.printstacktrace(system.out); throw (Exception)e.fillInStackTrace(); public static void main(string[] args) { g(); catch (Exception e) { System.out.println("main: printstacktrace()"); e.printstacktrace(system.out); h(); catch (Exception e) { System.out.println("main: printstacktrace()"); e.printstacktrace(system.out); at Rethrowing.f(Rethrowing.java:7) at Rethrowing.g(Rethrowing.java:11) at Rethrowing.main(Rethrowing.java:29) main: printstacktrace() java.lang.exception: thrown from f() 15 at Rethrowing.f(Rethrowing.java:7) at Rethrowing.g(Rethrowing.java:11) at Rethrowing.main(Rethrowing.java:29) originating the exception in f() Inside h(),e.printstacktrace() java.lang.exception: thrown from f() at Rethrowing.f(Rethrowing.java:7) at Rethrowing.h(Rethrowing.java:20) at Rethrowing.main(Rethrowing.java:35) main: printstacktrace() java.lang.exception: thrown from f() at Rethrowing.h(Rethrowing.java:24) at Rethrowing.main(Rethrowing.java:35)

16 Rethrowing a New Exception class OneException extends Exception { public OneException(String s) { super(s); class TwoException extends Exception { public TwoException(String s) { super(s); public class RethrowNew { public static void f() throws OneException { System.out.println("originating the exception in f()"); throw new OneException("thrown from f()"); public static void main(string[] args) { f(); catch (OneException e) { System.out.println( "Caught in inner try, e.printstacktrace()"); e.printstacktrace(system.out); throw new TwoException("from inner try"); catch (TwoException e) { System.out.println( "Caught in outer try, e.printstacktrace()"); e.printstacktrace(system.out); originating the exception in f() Caught in inner try, e.printstacktrace() OneException: thrown from f() at RethrowNew.f(RethrowNew.java:15) at RethrowNew.main(RethrowNew.java:20) Caught in outer try, e.printstacktrace() TwoException: from inner try at RethrowNew.main(RethrowNew.java:25) 16

17 Cleanup With Finally The finally clause provides a mechanism to take care of non-memory resources. Anything that must always be done should be included in the finally clause. The finally clause should not be used for operations that may not always be needed or appropriate. 17

18 Doesn t Always Work public class Switch { private boolean state = false; public boolean read() { return state; public void on() { state = true; print(this); public void off() { state = false; print(this); public String tostring() { return state? "on" : "off"; public class OnOffSwitch { private static Switch sw = new Switch(); public static void f() throws OnOffException1, OnOffException2 { public static void main(string[] args) { sw.on(); // Code that can throw exceptions... f(); sw.off(); catch (OnOffException1 e) { System.out.println("OnOffException1"); sw.off(); catch (OnOffException2 e) { System.out.println("OnOffException2"); sw.off(); 18

19 Always Works public class WithFinally { static Switch sw = new Switch(); public static void main(string[] args) { sw.on(); // Code that can throw exceptions... OnOffSwitch.f(); catch (OnOffException1 e) { System.out.println("OnOffException1"); catch (OnOffException2 e) { System.out.println("OnOffException2"); finally { sw.off(); 19

20 Inheritance Implications Overridden methods may only throw exceptions specified in the base-class version. Derived-class exceptions do not violate the rule. The restriction does not apply to constructors. Derived-class constructors must declare baseclass exeptions in their exception specification. 20

21 Constructors If a constructor throws an exception proper cleanup may not occur. Any sort of cleanup done in a finally clause should be executed conditionally and controlled by a flag. Only perform this cleanup in finally if you re forced to. 21

22 Cleanup Example public class InputFile { private BufferedReader in; public InputFile(String fname) throws Exception { in = new BufferedReader(new FileReader(fname)); /* Other code that might throw exceptions */ catch (FileNotFoundException e) { System.out.println("Could not open " + fname); // Wasn't open, so don't close it throw e; catch (Exception e) { // all other exceptions must close it in.close(); catch (IOException e2) { System.out.println("in.close() unsuccessful"); throw e; /* Rethrow */ finally { /* Don't close it here */ 22

23 The Rest of the Class public String getline() { String s; s = in.readline(); catch (IOException e) { throw new RuntimeException("readLine() failed"); return s; public void dispose() { in.close(); System.out.println("dispose() successful"); catch (IOException e2) { throw new RuntimeException("in.close() failed"); 23

24 Client Code public class Cleanup { public static void main(string[] args) { InputFile in = new InputFile("Cleanup.java"); String s; int i = 1; while ((s = in.getline())!= null) ; /* Perform line-by-line processing here... */ catch (Exception e) { System.out.println("Caught Exception in main"); e.printstacktrace(system.out); finally { in.dispose(); catch (Exception e) { System.out.println("InputFile construction failed"); 24

25 Exception Matching... Handlers are searched through in the order in which they were written. Derived-class exceptions match base-class handlers. The compiler will detect unreachable code. 25

26 ...Exception Matching class Annoyance extends Exception { class Sneeze extends Annoyance { public class Human { public static void main(string[] args) { // Catch the exact type: throw new Sneeze(); catch (Sneeze s) { System.out.println("Caught Sneeze"); catch (Annoyance a) { System.out.println("Caught Annoyance"); // Catch the base type: throw new Sneeze(); catch (Annoyance a) { System.out.println("Caught Annoyance"); 26

27 Avoiding the Issue Exceptions are harmful if swallowed: /*...to do something useful */ catch(exception e) { // Gulp! Or you can do nothing and get a stack trace: public class MainException { public static void main(string[] args) throws Exception { // Use the file... // Close the file: file.close(); 27

28 Converting an Exception You can turn a checked exception into a runtime exception: somethinguseful(); catch(idontknowwhattodowiththischeckedexception e) { throw new RunTimeException(e); 28

29 Overhead Exceptions are free as long as they don t get thrown. Thrown exceptions are expensive. Don t use exceptions for normal flow of control. Exceptions should only be used to handle abnormal conditions. 29

30 Guidelines Handle an exception only if there is enough information in the current context to correct the error. If not, allow it to propigate upward. Separated error handling from normal flow makes code more readable and maintainable. Handle complete tasks, not single statements in a try block. Resumption causes excessive coupling and is not available in C++/Java. Use loops to retry. 30

31 Guidelines Use exceptions in constructors if something could go wrong: people assume construction succeeds. If you catch an exception, do something with it; don t stub it out. Clean up using finally. 31

32 Summary Exception handling in Java is enforced by the compiler: they must be caught, exception specification must be provided. Error handling is clean and straightforward: error handling is left to the client programmer, how the client handles the error is decoupled from the implementation, the implementer knows that errors will be handled. If it seems like more work it s because you ve been ignoring errors. 32

엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University COPYRIGHTS 2017 EOM, HYEONSANG ALL RIGHTS RESERVED

엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University COPYRIGHTS 2017 EOM, HYEONSANG ALL RIGHTS RESERVED 엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University COPYRIGHTS 2017 EOM, HYEONSANG ALL RIGHTS RESERVED Outline - Interfaces - An Instrument interface - Multiple Inheritance

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

6.Introducing Classes 9. Exceptions

6.Introducing Classes 9. Exceptions 6.Introducing Classes 9. Exceptions Sisoft Technologies Pvt Ltd SRC E7, Shipra Riviera Bazar, Gyan Khand-3, Indirapuram, Ghaziabad Website: www.sisoft.in Email:info@sisoft.in Phone: +91-9999-283-283 Learning

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

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

A problem?... Exceptions. A problem?... A problem?... Suggested Reading: Bruce Eckel, Thinking in Java (Fourth Edition) Error Handling with Exceptions

A problem?... Exceptions. A problem?... A problem?... Suggested Reading: Bruce Eckel, Thinking in Java (Fourth Edition) Error Handling with Exceptions A problem?... Exceptions Suggested Reading: Bruce Eckel, Thinking in Java (Fourth Edition) Error Handling with Exceptions 2 A problem?... A problem?... 3 4 A problem?... A problem?... 5 6 A problem?...

More information

Object Oriented Software Design

Object Oriented Software Design Object Oriented Software Design Polymorphism, Abstract Classes, Interfaces Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa October 28, 2010 G. Lipari (Scuola Superiore Sant

More information

Object Oriented Software Design

Object Oriented Software Design Object Oriented Software Design Polymorphism, Abstract Classes, Interfaces Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa October 3, 2011 G. Lipari (Scuola Superiore Sant

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

Exceptions. Examples of code which shows the syntax and all that

Exceptions. Examples of code which shows the syntax and all that Exceptions Examples of code which shows the syntax and all that When a method might cause a checked exception So the main difference between checked and unchecked exceptions was that the compiler forces

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 - 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

Object oriented programming. Instructor: Masoud Asghari Web page: Ch: 7

Object oriented programming. Instructor: Masoud Asghari Web page:   Ch: 7 Object oriented programming Instructor: Masoud Asghari Web page: http://www.masses.ir/lectures/oops2017sut Ch: 7 1 In this slide We follow: https://docs.oracle.com/javase/tutorial/index.html Trail: Essential

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

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

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

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

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

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

Sri Vidya College of Engineering & Technology Question Bank

Sri Vidya College of Engineering & Technology Question Bank 1. What is exception? UNIT III EXCEPTION HANDLING AND I/O Part A Question Bank An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program s instructions.

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

Exceptions vs. Errors Exceptions vs. RuntimeExceptions try...catch...finally throw and throws

Exceptions vs. Errors Exceptions vs. RuntimeExceptions try...catch...finally throw and throws Lecture 14 Summary Exceptions vs. Errors Exceptions vs. RuntimeExceptions try...catch...finally throw and throws 1 By the end of this lecture, you will be able to differentiate between errors, exceptions,

More information

Exception Handling. --After creating exception object,method handover that object to the JVM.

Exception Handling. --After creating exception object,method handover that object to the JVM. Exception Handling 1. Introduction 2. Runtime Stack Mechanism 3. Default Exception Handling in Java 4. Exception Hirarchy 5. Customized Exception Handling By using -catch 6. Control flow in -catch 7. Methods

More information

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

Exceptions. Produced by. Introduction to the Java Programming Language. Eamonn de Leastar

Exceptions. Produced by. Introduction to the Java Programming Language. Eamonn de Leastar Exceptions Introduction to the Java Programming Language Produced by Eamonn de Leastar edeleastar@wit.ie Department of Computing, Maths & Physics Waterford Institute of Technology http://www.wit.ie http://elearning.wit.ie

More information

National University. Faculty of Computer Since and Technology Object Oriented Programming

National University. Faculty of Computer Since and Technology Object Oriented Programming National University Faculty of Computer Since and Technology Object Oriented Programming Lec (8) Exceptions in Java Exceptions in Java What is an exception? An exception is an error condition that changes

More information

16-Dec-10. Consider the following method:

16-Dec-10. Consider the following method: Boaz Kantor Introduction to Computer Science IDC Herzliya Exception is a class. Java comes with many, we can write our own. The Exception objects, along with some Java-specific structures, allow us to

More information

Chapter 14. Exception Handling and Event Handling ISBN

Chapter 14. Exception Handling and Event Handling ISBN Chapter 14 Exception Handling and Event Handling ISBN 0-321-49362-1 Chapter 14 Topics Introduction to Exception Handling Exception Handling in Ada Exception Handling in C++ Exception Handling in Java Introduction

More information

EXCEPTIONS. Objectives. The try and catch Statements. Define exceptions. Use try, catch and finally statements. Describe exception categories

EXCEPTIONS. Objectives. The try and catch Statements. Define exceptions. Use try, catch and finally statements. Describe exception categories Objectives Define exceptions 8 EXCEPTIONS Use try, catch and finally statements Describe exception categories Identify common exceptions Develop programs to handle your own exceptions 271 272 Exceptions

More information

EXCEPTIONS. Java Programming

EXCEPTIONS. Java Programming 8 EXCEPTIONS 271 Objectives Define exceptions Exceptions 8 Use try, catch and finally statements Describe exception categories Identify common exceptions Develop programs to handle your own exceptions

More information

EXCEPTION-HANDLING INTRIVIEW QUESTIONS

EXCEPTION-HANDLING INTRIVIEW QUESTIONS EXCEPTION-HANDLING INTRIVIEW QUESTIONS Q1.What is an Exception? Ans.An unwanted, unexpected event that disturbs normal flow of the program is called Exception.Example: FileNotFondException. Q2.What is

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

Defensive Programming. Ric Glassey

Defensive Programming. Ric Glassey Defensive Programming Ric Glassey glassey@kth.se Outline Defensive Programming Aim: Develop the programming skills to anticipate problems beyond control that may occur at runtime Responsibility Exception

More information

Exceptions Handling Errors using Exceptions

Exceptions Handling Errors using Exceptions Java Programming in Java Exceptions Handling Errors using Exceptions Exceptions Exception = Exceptional Event Exceptions are: objects, derived from java.lang.throwable. Throwable Objects: Errors (Java

More information

Java Exceptions Java, winter semester

Java Exceptions Java, winter semester Java Exceptions 1 Exceptions errors reporting and handling an exception represents an error state of a program exception = an instance of java.lang.throwable two subclasses java.lang.error and java.lang.exception

More information

Lecture 14 Summary 3/9/2009. By the end of this lecture, you will be able to differentiate between errors, exceptions, and runtime exceptions.

Lecture 14 Summary 3/9/2009. By the end of this lecture, you will be able to differentiate between errors, exceptions, and runtime exceptions. Lecture 14 Summary Exceptions vs. Errors Exceptions vs. RuntimeExceptions...catch...finally throw and throws By the end of this lecture, you will be able to differentiate between errors, exceptions, and

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

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

Day 8. COMP1006/1406 Summer M. Jason Hinek Carleton University

Day 8. COMP1006/1406 Summer M. Jason Hinek Carleton University Day 8 COMP1006/1406 Summer 2016 M. Jason Hinek Carleton University today s agenda assignments Assignment 4 is out and due on Tuesday Bugs and Exception handling 2 Bugs... often use the word bug when there

More information

OBJECT ORIENTED PROGRAMMING. Course 6 Loredana STANCIU Room B616

OBJECT ORIENTED PROGRAMMING. Course 6 Loredana STANCIU Room B616 OBJECT ORIENTED PROGRAMMING Course 6 Loredana STANCIU loredana.stanciu@upt.ro Room B616 Exceptions An event, which occurs during the execution of a program, that disrupts the normal flow of the program's

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

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

Exceptions. Produced by. Algorithms. Eamonn de Leastar Department of Computing, Maths & Physics Waterford Institute of Technology

Exceptions. Produced by. Algorithms. Eamonn de Leastar Department of Computing, Maths & Physics Waterford Institute of Technology Exceptions Algorithms Produced by Eamonn de Leastar edeleastar@wit.ie Department of Computing, Maths & Physics Waterford Institute of Technology http://www.wit.ie http://elearning.wit.ie Exceptions ± Definition

More information

ASSERTIONS AND LOGGING

ASSERTIONS AND LOGGING SUMMARY Exception handling, ASSERTIONS AND LOGGING PROGRAMMAZIONE CONCORRENTE E DISTR. Università degli Studi di Padova Dipartimento di Matematica Corso di Laurea in Informatica, A.A. 2015 2016 rcardin@math.unipd.it

More information

JAC444 - Lecture 4. Segment 1 - Exception. Jordan Anastasiade Java Programming Language Course

JAC444 - Lecture 4. Segment 1 - Exception. Jordan Anastasiade Java Programming Language Course JAC444 - Lecture 4 Segment 1 - Exception 1 Objectives Upon completion of this lecture, you should be able to: Separate Error-Handling Code from Regular Code Use Exceptions to Handle Exceptional Events

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

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

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 CSCI 201 Principles of Software Development

Exception Handling CSCI 201 Principles of Software Development Exception Handling CSCI 201 Principles of Software Development Jeffrey Miller, Ph.D. jeffrey.miller@usc.edu Outline Program USC CSCI 201L 2/19 Exception Handling An exception is an indication of a problem

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

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

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

CS 61B Data Structures and Programming Methodology. July 7, 2008 David Sun

CS 61B Data Structures and Programming Methodology. July 7, 2008 David Sun CS 61B Data Structures and Programming Methodology July 7, 2008 David Sun Announcements You ve started (or finished) project 1, right? Package Visibility public declarations represent specifications what

More information

Exception Handling. Content 25/03/15. Advanced Programming

Exception Handling. Content 25/03/15. Advanced Programming Exception Handling Advanced Programming 1 25/03/15 2 Content Introduction The concept of error handling The concept of exception Exception handlers Stack unwinding mechanism Java checked and unchecked

More information

2.6 Error, exception and event handling

2.6 Error, exception and event handling 2.6 Error, exception and event handling There are conditions that have to be fulfilled by a program that sometimes are not fulfilled, which causes a so-called program error. When an error occurs usually

More information

Exceptions Questions https://www.journaldev.com/2167/java-exception-interview-questionsand-answers https://www.baeldung.com/java-exceptions-interview-questions https://javaconceptoftheday.com/java-exception-handling-interviewquestions-and-answers/

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

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

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

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

Software Practice 1 - Error Handling Exception Exception Hierarchy Catching Exception Userdefined Exception Practice#5

Software Practice 1 - Error Handling Exception Exception Hierarchy Catching Exception Userdefined Exception Practice#5 1 Software Practice 1 - Error Handling Exception Exception Hierarchy Catching Exception Userdefined Exception Practice#5 Prof. Hwansoo Han T.A. Jeonghwan Park 41 T.A. Sung-in Hong 42 2 Exception An exception

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

I/O. Output. Input. Input ของจาวา จะเป น stream จะอ าน stream ใช คลาส Scanner. standard input. standard output. standard err. command line file.

I/O. Output. Input. Input ของจาวา จะเป น stream จะอ าน stream ใช คลาส Scanner. standard input. standard output. standard err. command line file. I/O and Exceptions I/O Input standard input keyboard (System.in) command line file Output standard output Screen (System.out) standard err file System.err Input ของจาวา จะเป น stream จะอ าน stream ใช คลาส

More information

Exception Handling Advanced Programming Techniques

Exception Handling Advanced Programming Techniques Exception Handling Advanced Programming Techniques https://no.wikipedia.org/wiki/tastatur#/media/file:computer_keyboard.png Prof. Dr. Bernhard Humm FB Informatik, Hochschule Darmstadt 1 Agenda Motivation

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

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

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

Exceptions in Java

Exceptions in Java Exceptions in Java 3-10-2005 Opening Discussion Do you have any questions about the quiz? What did we talk about last class? Do you have any code to show? Do you have any questions about the assignment?

More information

Chapter 3 Java Exception

Chapter 3 Java Exception Chapter 3 Java Exception J AVA C O S E @ Q Q. C O M Content A Notion of Exception Java Exceptions Exception Handling User-defined Exceptions How to Use Exception 2 COSE Java Exceptional Condition Divided

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

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

Software Practice 1 - Error Handling

Software Practice 1 - Error Handling Software Practice 1 - Error Handling Exception Exception Hierarchy Catching Exception Userdefined Exception Practice#5 Prof. Joonwon Lee T.A. Jaehyun Song Jongseok Kim (42) T.A. Sujin Oh Junseong Lee 1

More information

Exceptions. What exceptional things might our programs run in to?

Exceptions. What exceptional things might our programs run in to? Exceptions What exceptional things might our programs run in to? Exceptions do occur Whenever we deal with programs, we deal with computers and users. Whenever we deal with computers, we know things don

More information

Inheritance. SOTE notebook. November 06, n Unidirectional association. Inheritance ("extends") Use relationship

Inheritance. SOTE notebook. November 06, n Unidirectional association. Inheritance (extends) Use relationship Inheritance 1..n Unidirectional association Inheritance ("extends") Use relationship Implementation ("implements") What is inherited public, protected methods public, proteced attributes What is not inherited

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

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

Writing your own Exceptions. How to extend Exception

Writing your own Exceptions. How to extend Exception Writing your own Exceptions How to extend Exception When would you write your own exception class? When to write your own custom exception is a matter for discussion in your project design team. There

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

Java Strings Java, winter semester

Java Strings Java, winter semester Java Strings 1 String instances of java.lang.string compiler works with them almost with primitive types String constants = instances of the String class immutable!!! for changes clases StringBuffer, StringBuilder

More information

Unit 4. Exception handling mechanism. new look try/catch mechanism in Java Enumeration in Java 5 - usage.

Unit 4. Exception handling mechanism. new look try/catch mechanism in Java Enumeration in Java 5 - usage. Unit 4 Exception handling mechanism. new look try/catch mechanism in Java Enumeration in Java 5 - usage. exceptions An exception is an abnormal condition that arises in a code sequence at run time. an

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

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

Relation Overriding. Syntax and Semantics. Simple Semantic Domains. Operational Semantics

Relation Overriding. Syntax and Semantics. Simple Semantic Domains. Operational Semantics SE3E03, 2006 1.59 61 Syntax and Semantics Syntax Shape of PL constructs What are the tokens of the language? Lexical syntax, word level How are programs built from tokens? Mostly use Context-Free Grammars

More information

CS193j, Stanford Handout #25. Exceptions

CS193j, Stanford Handout #25. Exceptions CS193j, Stanford Handout #25 Summer, 2003 Manu Kumar Exceptions Great Exceptations Here we'll cover the basic features and uses of exceptions. Pre-Exceptions A program has to encode two ideas -- how to

More information

Exceptions. Errors and Exceptions. Dealing with exceptions. What to do about errors and exceptions

Exceptions. Errors and Exceptions. Dealing with exceptions. What to do about errors and exceptions Errors and Exceptions Exceptions An error is a bug in your program dividing by zero going outside the bounds of an array trying to use a null reference An exception is a problem whose cause is outside

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

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

CSE 331 Software Design & Implementation

CSE 331 Software Design & Implementation CSE 331 Software Design & Implementation Hal Perkins Spring 2017 Exceptions and Assertions 1 Outline General concepts about dealing with errors and failures Assertions: what, why, how For things you believe

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

Java Loose Ends. 11 December 2017 OSU CSE 1

Java Loose Ends. 11 December 2017 OSU CSE 1 Java Loose Ends 11 December 2017 OSU CSE 1 What Else? A few Java issues introduced earlier deserve a more in-depth treatment: Try-Catch and Exceptions Members (static vs. instance) Nested interfaces and

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

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

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

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

Internal Classes and Exceptions

Internal Classes and Exceptions Internal Classes and Exceptions Object Orientated Programming in Java Benjamin Kenwright Outline Exceptions and Internal Classes Why exception handling makes your code more manageable and reliable Today

More information

Lecture 20. Java Exceptional Event Handling. Dr. Martin O Connor CA166

Lecture 20. Java Exceptional Event Handling. Dr. Martin O Connor CA166 Lecture 20 Java Exceptional Event Handling Dr. Martin O Connor CA166 www.computing.dcu.ie/~moconnor Topics What is an Exception? Exception Handler Catch or Specify Requirement Three Kinds of Exceptions

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

Java Programming Unit 7. Error Handling. Excep8ons.

Java Programming Unit 7. Error Handling. Excep8ons. Java Programming Unit 7 Error Handling. Excep8ons. Run8me errors An excep8on is an run- 8me error that may stop the execu8on of your program. For example: - someone deleted a file that a program usually

More information