Typecasts and Dynamic Dispatch. Dynamic dispatch
|
|
- Kelly Sparks
- 5 years ago
- Views:
Transcription
1 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 at compile-time. By writing (T) e we state that T should be the type of e at this point in the code where e is used. T must either be a supertype of (called an upcast) or conform with (called a downcast) the declared type of e. Easy explanation: Both types must lie on the same path connecting a leaf and the root (Object) in the inheritance tree. 1 2 Upcasts always works (Need not be explicit) An upcast Dynamic dispatch A Super Sub Super s1 (Super) new Sub (); Sub s2 = (Sub) s1; A downcast Needed to state that the type on the right-hand side conforms with the type on the left. H G F D C B J I L M N O Works at run-time because the type of the dynamic object referred to by s1 conforms with Sub. (In general: If not, there will be a run-time error.) Works at compile-time because the type of s1 is a supertype of Sub. Downcasts must be written in Java to have the programmer explicitly guarantee to 1. the compiler, and 2. fellow programmers, that the types indeed do conform. (Upcast; no need to be explicit here) E E x = new E(); x.f(); C x = new E(); x.f(); D x = new D(); x.f(); B x = new K(); x.f(); K P M x = new M(); x.f(); B x = new O(); ((L) x).f(); 3 (Downcast; N, M, and B also works at run-time but not P) 4
2 An Example to Try in Eclipse 1. Abstraction A B C D E F package l08.dynamicdispatch; public class Main { public static void main(string[] args) { A x = new E(); ((C) x).f(); } } class A { void f() { System.out.println("A"); } } class B extends A { void f() { System.out.println("B"); } } class C extends B { void f() { System.out.println("C"); } } class D extends C { void f() { System.out.println("D"); } } class E extends D { void f() { System.out.println("E"); } } class F extends E { void f() { System.out.println("F"); } } We all have an ability to disregard unimportant details in favour of the important. We can focus our attention. Our perception of the World is much filtered, it seems. Our senses do this automatically for us. Although your eyes "see" everything in front of you, the brain "ignores" everything except for a few important details. We can also control this filtering, to some degree. We can train ourselves, learn. We can also, it seems, control not only what we disregard and perceive but also how. This is probably a factor that has helped us survive as a spieces. 5 6 Abstraction Abstraction and programming We apply abstraction whenever we name things and just use the names without giving all the details. Very practical This is also true in programming where languages provide means to abstract away from the computer. Early inventions such as variables and methods are, for instance, nothing but abstractions of computer memory (data and code). Abstraction in programming allows us to disregard details in how computers work and instead focus on the problems we like to solve. We build models of real-world entities, define operations that mimic possible actions in the real world, and express real-world interactions between entities in code. Object-oriented programming provides the (so far) best tools for doing this. In object-oriented programming a most useful abstraction is an abstract view on a class. 7 8
3 Needed to write large programs Two different views on a class The abstract view An external description. WHAT a class represents and WHAT its function is. Needed by someone who likes to use the class. Format: UML-diagrams Abstract data types The implementation view An internal description. HOW it works and HOW variables, methods etc are implemented. Needed by someone who likes to re-program the class. Format: Source code Any programmer that writes software that uses a class is a client, the software is client code, and the class is a supplier class. Usually the focus in plain programming courses 9 2. Abstract Data Types An abstract data type (ADT) is a triplet containing 1) a set of values, A well-defined domain. Ex: Time of day in terms of hours and minutes. 2) a set of operations on the values, and Ex: inchour() and incminute() that increases the hour and minute by one unit respectively. 3) a set of axioms. Truths about the operations and the set of values. Ex: The hour is always 0, 23, or in-between these two values. If the clock is one minute to a whole hour, incminute() results in the minute being reset to zero. An ADT is a mathematical object used to reason about programs. 10 ADT:s and Program Design The rigor by which ADT:s can be defined have proved extremely useful to programmers. An ADT captures the fundamental functionality of the program. They are theoretical representations and a basis for proving program properties. Object-oriented programming much amounts to identifying these ADT:s and how they are used, and to program them properly. Some Common (General) ADT:s Container, Deque, List, Map (also called Dictionary), Multimap, Multiset, Priority queue, Queue, Set, Stack, String, and Tree. These are good building blocks to start from. Many are included in Java s standard library. But a programmer most often need to come up with new, different and sometimes tailor-made, ADT:s
4 Design and implementation Design determines the software s architecture. (What task does the software perform?) ADT Associated Operations Class Diagram myclass + type var1 Class Specification domain & class invariant Code public class myclass {... } Implementation determines the software s code. (How does the software perform its task?) Data + type method() + void method2(parm) method2(parm) pre:... modifies:... post: The Object of Data Abstraction and Structure, David D. Riley Addison Wesley pub. Design Implementation 14 Software specification Implementing ADT:s in Java Often written in the source code as comments. Mimics the ADT. Contains A domain Provides an abstract view on the state. Need not exist in the implementation view() Used to express invariants and pre/post conditions. Most often Mathematical types, sets, sequences. Class invariants. Everything relevant that stays invariant through-out the life of a dynamic object of this class, pre- and postconditions for methods. As for an abstract view versus an implementation view, a specification separates WHAT from HOW. Ordinary classes could work fine but rather implement ADT:s either as abstract classes or interfaces. Then, the implementation can be provided in the form of a concrete class that extends the abstract class (or implements the interface). We can have many different classes implementing the same ADT One being a fast initial hack due to lack of time, another a bit slow but 100% correct, yet another very efficient but only believed to work, Flexibility a fourth implementation using a totally different approach, etc Even more importantly, if clients only program using the abstract class/the interface, any of our concrete classes can be used in the end 15 16
5 Queue q = new FIFO(); (for example) Also, FastQ or DebugQueue could be used here. X <<interface>> Queue +isempty() : boolean +size() : int... FIFO FastQ DebugQueue Because of the inheritance relation, FIFO, FastQ, and DebugQueue can all be used where a Queue can be used. Why ADT:s? Things that belong together are grouped together. Easier to change a program. Gives overview. Small, graspable ADT:s are easy to understand and work with. Enables simultaneous work on parts of programs. Could start with a simple implementation and change it independently of other parts. ==> Very good for cooperation Advice about ADT:s Its better with a large number of small ADT:s than a small number of large ones. Large ones are hard to overview and program correctly. When designing ADT:s abstract away details (hide them), be precise (well-written specifications, invariants and axioms), and design with the intend to re-use the ADT:s over and over again in the future. 19 In this example, operation1(), operation2(), are abstract, templatemethod is not. 3. Template Design Pattern templatemethod() is inherited as it is, while the operations are declared (made concrete). (The templatemethod() could also be shadowed, totally redefining it. This is a usual practice.) ( operation1(), operation2(), are used here only as an example) operation1(), operation2() could have different definitions here resulting in different behavior of the inherited templatemethod(). (Because of dynamic dispatch.) 20
6 4. Program robustness Good programs are robust. They handle unexpected errors and exceptional situations well during run-time. Traditionally, methods return error codes when they detect errors. Drawback: Callers have to check for errors, which results in massive amounts of extra code in methods. Java (and other modern languages) provides another kind of support for detecting, handling, and recovering from run-time errors: Exceptions. Exceptions An exception corresponds to a run-time error, for instance Attempted division by zero. Attempted read from a non-existent file. Attempted access to an array cell that does not exist (invalid index). etc It is represented by a dynamic object of the class Throwable. Rather: A subclass of Throwable Common Exceptions ArithmeticException A calculation gone wrong, like division with zero. ClassCastException Bad type cast. NullPointerException Attempted use of a reference variable that is null. IOException Errors that has to do with input and output to/from files, streams, the keyboard etc
7 Detection of Exceptions When an error is detected, an exception is thrown and normal program execution is interrupted. An immediate return through all methods that have been called is started. If a has called b, that has called c, that has called d, and an exception occurs in d, the sequence back is c- b- a. This stops as soon as a method that handles the exception is encountered or the main-method is reached (and the program halts). Most exceptions are thrown automatically when an error occurs. public class Main { public static void main(string[] args) { System.out.println("Before..."); Anders a = new Anders(); // line 4 System.out.println("... After."); } } class Anders { public Anders() { Bertil b = new Bertil(); // line 11 } } class Bertil { public Bertil() { int ludde = 12; ludde = ludde / 0; // line 18, division by 0 } } Before... Exception in thread "main" java.lang.arithmeticexception: / by zero at Bertil.<init>(Main.java:18) at Anders.<init>(Main.java:11) at Main.main(Main.java:4) Explicit Exceptions Exceptions can also be thrown explicitly: public class Main { public static void main(string[] args) { System.out.println("Before..."); Anders a = new Anders(); // line 4 System.out.println("... After."); } } class Anders { public Anders() { Bertil b = new Bertil(); // line 11 } } class Bertil { public Bertil() { int ludde = 12; ludde = ludde / 0; // line 18, division by 0 } } A traceback (stack trace) throw new ExceptionKind( Error msg ); throw new ExceptionKind(); These exceptions are generated by the program itself
8 public class Main { public static void main(string[] args) { System.out.println("Before..."); Anders a = new Anders(); System.out.println("... After."); } } class Anders { public Anders() { Bertil b = new Bertil(); } } class Bertil { public Bertil() { throw new RuntimeException("Just joking"); } } Before... Exception in thread "main" java.lang.runtimeexception: Just joking at Bertil.<init>(Main.java:17) at Anders.<init>(Main.java:11) at Main.main(Main.java:4) public class Main { public static void main(string[] args) { System.out.println("Before..."); Anders a = new Anders(); System.out.println("... After."); } } class Anders { public Anders() { Bertil b = new Bertil(); } } class Bertil { public Bertil() { throw new RuntimeException("Just joking"); } } Uncaught Exceptions Caught Exceptions An uncaught exception is handled by the Java virtual machine and results in program termination. And a traceback as shown. Like the previous examples. Many errors like Out of memory or No such class should be uncaught. There is not much a program can do about such errors but to terminate. Many times it is, however, preferable to handle an error in the program. Should be done if it is easy to recover from the error. Some exceptions are also thrown deliberately to be handled by other parts of the program. Then, the program should catch [the thrown] exception. This is done in a try-catch statement
9 public class Main { public static void main(string[] args) { System.out.println("Before..."); Anders a = new Anders(); System.out.println("... After."); } } class Anders { public Anders() { try { Bertil b = new Bertil(); System.out.println( No error ); } catch (RuntimeException e) { System.out.println("Ohps An error occured."); } } } class Bertil { public Bertil() { throw new RuntimeException("Just joking"); } } 33 1) Note the absence of a line containing No error Since an exception was thrown we never reached the line where this should have been printed. 2) The error message (the traceback) is not printed since we handle the exception on our own. 3) The program terminates normally. without a stack trace. Result Before... Ohps An error occured.... After. public class Main { public static void main(string[] args) { System.out.println("Before..."); Anders a = new Anders(); System.out.println("... After."); } } class Anders { public Anders() { try { Bertil b = new Bertil(); System.out.println( No error ); } catch (RuntimeException e) { System.out.println("Ohps An error occured."); } } } class Bertil { public Bertil() { throw new RuntimeException("Just joking"); } } 34 Checked and Unchecked" Standard Exceptions Checked exceptions must either 1) be caught using try-catch in a method, or 2) be listed in a throws clause of any method that may throw (propagate) them public void doit() throws IOException { // code that could cause an IOException } leaving the exception handling to the caller. Unchecked exceptions need not be caught. If a client can reasonably be expected to recover from an exception, make it a checked exception. Example: IOException If a client cannot do anything to recover from the exception, make it an unchecked exception. Example: Division by zero, array index out of bounds. 35 Must be handled 36
10 5. Basic I/O in Java "I/O" means "Input and Output" and how a Java program communicates with storage devices and the outer world. System.out.println is one way. Chapter 10 in Eck and Pillay, Part 2 in the course compendium. Needed in lab 3. (Reading from text files in GraphIO.) Use the Scanner class in the package java.util() Read Ch. 10 (and use Google ) to learn how. 37 Scanner package l08.scanner; import java.io.*; import java.util.*; public class StdIOTest { public static void main(string arg[]) { boolean stop = false, first = true; Scanner scanner = new Scanner(System.in); while (stop) { try { if (first) { System.out.printf("Input an integer: "); first = false; } else { System.out.printf("Input another integer: "); } int int_val = scanner.nextint(); System.out.println("Thank you. You entered " + int_val + "\n"); } catch (InputMismatchException e) { System.out.println("That is not an integer. Program terminates."); stop = true; } } } } 38 Reading from a file package l08.scanner; import java.io.file; import java.io.filenotfoundexception; import java.util.scanner; public class FileRead { public static void main(string arg[]) { try { File file = new File("src/l08/scanner/FileRead.java"); Scanner scanner = new Scanner(file); while (scanner.hasnext()) { System.out.println("-->" + scanner.next() + "<--"); } scanner.close(); } catch (FileNotFoundException e) { System.out.println("Can't open file. Program terminates."); } } } 39
Lecture 8. Lecture
Abstract Data Type (ADT) Abstract Class Design PaIern Template Design PaIern Abstrac8on More on Typecasts and Dynamic Dispatch D0010E Program Robustness Excep2ons Review: I/O - Håkan Jonsson 1 1 1. Typecasts
More informationBBM 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 informationCOE318 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 informationProgramming 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 informationProgramming 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 informationCSC 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 informationLe 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 informationA 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 informationCS115. 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 informationChapter 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 informationChapter 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 informationExceptions - 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 informationMore 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 informationExceptions 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 informationBBM 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 informationCSCI 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 informationAdministration. 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 informationNational 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 informationComp 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 informationMore 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 informationCOMP-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 informationITI 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 informationExceptions 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 informationException-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 informationITI 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 informationEXCEPTION 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 informationProgram Correctness and Efficiency. Chapter 2
Program Correctness and Efficiency Chapter 2 Chapter Objectives To understand the differences between the three categories of program errors To understand the effect of an uncaught exception and why you
More informationAbout 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 informationIntroduction to Computer Science II CS S-22 Exceptions
Introduction to Computer Science II CS112-2012S-22 Exceptions David Galles Department of Computer Science University of San Francisco 22-0: Errors Errors can occur in program Invalid input / bad data Unexpected
More informationC16b: 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 informationLecture 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 informationCS 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 informationWhat 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 informationWhat 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 informationChapter 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 informationObject 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 informationIntroduction Unit 4: Input, output and exceptions
Faculty of Computer Science Programming Language 2 Object oriented design using JAVA Dr. Ayman Ezzat Email: ayman@fcih.net Web: www.fcih.net/ayman Introduction Unit 4: Input, output and exceptions 1 1.
More informationInheritance. 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 informationLecture 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 informationLecture 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 informationCOSC 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 informationCS159. 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 informationCMSC131. 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 informationECE 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 informationI/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 informationI/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 informationAssoc. 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 informationExceptions. 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 informationCS S-22 Exceptions 1. Running a web server, don t want one piece of bad data to bring the whole thing down
CS112-2012S-22 Exceptions 1 22-0: Errors Errors can occur in program Invalid input / bad data Unexpected situation Logic error in code Like to handle these errors gracefully, not just halt the program
More informationCOMP-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 informationFundamentals 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 information17. 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 informationCOMP 213. Advanced Object-oriented Programming. Lecture 17. Exceptions
COMP 213 Advanced Object-oriented Programming Lecture 17 Exceptions Errors Writing programs is not trivial. Most (large) programs that are written contain errors: in some way, the program doesn t do what
More information9. Java Errors and Exceptions
Errors and Exceptions in Java 9. Java Errors and Exceptions Errors and exceptions interrupt the normal execution of the program abruptly and represent an unplanned event. Exceptions are bad, or not? Errors,
More informationExceptions 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 informationIntroductory 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 informationChapter 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 informationChapter 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 informationObject 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 informationEXCEPTIONS. 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 informationJava 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 informationCOMP-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 informationChapter 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 informationExceptions. 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 informationExceptions, 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 informationIntroduction 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 informationEXCEPTION 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 information7. Java Input/Output. User Input/Console Output, File Input and Output (I/O)
116 7. Java Input/Output User Input/Console Output, File Input and Output (I/O) 117 User Input (half the truth) e.g. reading a number: int i = In.readInt(); Our class In provides various such methods.
More informationCS112 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 informationTopic 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 informationProgramming Languages and Techniques (CIS120)
Programming Languages and Techniques (IS120) Lecture 30 April 4, 2016 Exceptions hapter 27 HW7: PennPals hat Due: Tuesday Announcements Simplified Example class { public void foo() {.bar(); "here in foo");
More informationCSC 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 informationAP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS
AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS PAUL L. BAILEY Abstract. This documents amalgamates various descriptions found on the internet, mostly from Oracle or Wikipedia. Very little of this
More informationCSC207H: 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 informationCS 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 informationFull 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 informationException 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 informationExceptions. 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 information6. Java Errors and Exceptions
Errors and Exceptions in Java 6. Java Errors and Exceptions Errors and exceptions interrupt the normal execution of the program abruptly and represent an unplanned event. Exceptions are bad, or not? Errors,
More informationAbstraction. Implementation view. Abstract view. An ADT is a. Concrete Data Type. Public interface
Riley O5 & 1 Abstract Data Type (ADT) Template Design Pattern Abstraction Abstraction SMD135/167 Lecture 3 Interfaces Review: I/O Math: f(x)=x+4 is an abstraction f(3) is an application (of f on 3) 3+4
More informationObject Oriented Programming
Object Oriented Programming Java lecture (10.1) Exception Handling 1 Outline Exception Handling Mechanisms Exception handling fundamentals Exception Types Uncaught exceptions Try and catch Multiple catch
More informationExcep&ons and file I/O
Excep&ons and file I/O 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 informationIntroduction. 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 informationCSE 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 informationExceptions 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 informationSri 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 informationCOMP1008 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 informationData 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엄현상 (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 informationInput, Output and Exceptions. COMS W1007 Introduction to Computer Science. Christopher Conway 24 June 2003
Input, Output and Exceptions COMS W1007 Introduction to Computer Science Christopher Conway 24 June 2003 Input vs. Output We define input and output from the perspective of the programmer. Input is data
More informationWeiss Chapter 1 terminology (parenthesized numbers are page numbers)
Weiss Chapter 1 terminology (parenthesized numbers are page numbers) assignment operators In Java, used to alter the value of a variable. These operators include =, +=, -=, *=, and /=. (9) autoincrement
More informationAssertions and Exceptions Lecture 11 Fall 2005
Assertions and Exceptions 6.170 Lecture 11 Fall 2005 10.1. Introduction In this lecture, we ll look at Java s exception mechanism. As always, we ll focus more on design issues than the details of the language,
More informationCS1020 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 informationCorrectness 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 informationExceptions 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 informationSchool of Informatics, University of Edinburgh
CS1Ah Lecture Note 29 Streams and Exceptions We saw back in Lecture Note 9 how to design and implement our own Java classes. An object such as a Student4 object contains related fields such as surname,
More informationObject Oriented Programming
Object Oriented Programming Java lecture (10.2) Exception Handling 1 Outline Throw Throws Finally 2 Throw we have only been catching exceptions that are thrown by the Java run-time system. However, it
More informationInternal 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 informationException 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 informationDesigning Robust Classes
Designing Robust Classes Learning Goals You must be able to:! specify a robust data abstraction! implement a robust class! design robust software! use Java exceptions Specifications and Implementations
More information