School of Informatics, University of Edinburgh
|
|
- Tyrone Simon
- 5 years ago
- Views:
Transcription
1 CS1Bh Solution Sheet 4 Software Engineering in Java This is a solution set for CS1Bh Question Sheet 4. You should only consult these solutions after attempting the exercises. Notice that the solutions are samples alternative answers may be possible. 1. State whether each of these statements is true or false. Give a reason for your answer. a) A superclass typically represents a larger number of objects than its subclass represents. True. Every object that extends the subclass also extends the superclass, but the superclasses may have many unrelated subclasses. b) A subclass typically encapsulates less functionality than does its superclass. False. A subclass inherits all the functionality of its superclass. c) An object of a given subclass also belongs to the subclass s superclass. True. An object belongs to its class, that class s superclass, that superclass s superclass... The same also goes for interfaces. If a class implements an interface it must also implement every interface above it in the class hierarchy. d) Every class has a superclass. Almost true. Every class extends java.lang.object. Hence every class has at least this as a superclass. The only exception being Object itself. 2. Java provides interfaces and abstract classes as two ways of specifying behaviour of methods in classes without providing an implementation. What are the differences between the two? When would you prefer to use one or the other? There are two principal differences between interfaces and abstract classes. Firstly, interfaces are forbidden to provide any implementation of the methods they declare, whereas an abstract class can provide as much implementation as it wants. Furthermore interfaces may not declare constructors at all, even without a body. 1
2 The second difference is that classes can extend at most one class 1, whereas they can implement arbitrarily many interfaces. Conceptually interfaces correspond to abilities of the class (X implements Y meaning X can do Y ) whereas subclassing states what kind of thing a class is (X extends Y meaning X is a Y ). Prefer to use an abstract class to: provide some of the implementation. specify constructors of a certain form. enforce the is a relationship. Prefer an interface to: inherit functionality from another class maximise the number of classes which can conform to this specification 3. Programming exercises in CS1 use a relatively small number of classes, which have been compiled in a single directory. In the real world, however, Java programs may have hundreds of classes and interface definitions for an extreme example think how many classes are in the standard API. To organise classes in a useful fashion we use packages. A package is just a collection of classes which are in some way related 2. However the use of packages makes compiling and running Java programs a bit more complicated. Consider these two files, packtest1.java and packtest2.java: package A; // this tells the compiler which package // the classes defined in this file belong to class Test { public static void main (String[] args) { System.out.println("package A"); package B; class Test { public static void main (String[] args) { System.out.println("package B"); Try compiling and running them. Where are the class files put? What happens when you try to run them? Look at the manpages for javac and java and work out what you must do to compile and run the programs correctly. If we simply use the command 1 in fact all classes extend exactly one class, since if the extends keyword is not used, the class implicitly extends java.lang.object. 2 Actually packages are more than just an organisational convenience; being a member of a package gives a class special privileges with respect to other classes in the same package. 2
3 javac packtest1.java packtest2.java then only one class file is produced, in the current directory, called Test.class. If we run it then we get a fatal exception: [cookies]rwd: java Test Exception in thread "main" java.lang.noclassdeffounderror: test (wrong name: B/te The soluion is to compile the classes using the -d switch of javac. For example mkdir /myclasses javac -d /myclasses/ packtest1.java packtest2.java (where we have to create the directory first with mkdir if it doesn t already exist). Now the class files are in the directories /myclasses/a and /myclasses/b. But now the interpreter doesn t know where to find the class files. We have to invoke it with (eg) java -cp /myclasses/ A.Test or else set the CLASSPATH variable to include /myclasses/. Of course if we compiled the files with -d. then there is no need to specify the classpath as it will be the current directory. Now consider another file packtest3.java: package A; class Subtest { public static void main (String[] args) { Test t = new Test(); System.out.println("subtest OK"); Do you encounter any problems compiling it? Why? Again refer to the man page to resolve the problem. The most likely compilation problem is that javac needs to know where the class A.Test is. This can be done by setting the classpath either as an environment variable, or as a command line argument. javac -classpath /myclasses -d /myclasses packtest3.java Once you have sucessfully compiled it modify the file to use the defintion of test in packtest2.java. There are several ways to do this. How many can you think of? (You should get at least two.) Do you also need to modify packtest2.java? What changes are needed? To use the B.Test class either: a) use the full class name at line 5 e.g. B.Test t =... b) import the class: import B.Test; at the top of the file. 3
4 c) import the whole package: import B.*; d) move subtest to the other package by modifying its package statement. (Though in a real program you wouldn t usually want to do this.) These changes are not enough on their own; B.Test is not a public class. As well as changing its declaration it needs to be put in a file called Test.java. 4. Classes use the visibility modifiers public, private and protected to control which of their elements are available to other classes. What are the meanings of these modifiers? If a class does not sport any visibility modifier are there any restrictions on where it may be accessed from? What are they? Private classes, fields and methods are accessible only with in the class they are declared in. In particular they are not available to subclasses of the declaraing class. The default visibility (sometimes called package visibility) allows a class, field or method to be accessed anywhere within the same package as the declaring class. Protected classes, fields and methods are accessible within classes in the package of the declaring class and its subclasses, but not elsewhere. Public classes, fields and methods are accessible by any class in any package. 5. Consider this implementation of an Integer array. public class MyArray { public int size; private Integer[] array; public MyArray (int size) { this.size = size; array = new Integer[this.size]; public void put (Integer n, int pos) { if(pos >= 0 && pos < size) { array[pos]=n; public Integer get (int pos) { return array[pos]; 4
5 The file will compile, and in most circumstances it will function without problem. However it contains several flaws from an engineering point of view. How many can you identify? Note: this question has been modified since the sheet was originally issued. In particular the put method has been altered and the third flaw idenitified in these solution applies only to this altered version. a) The most serious error is making the size field public. This permits the user to write code like: MyArray M = new MyArray(5); M.size = 10; M.put(new Integer(101), 9); which will cause the program to try and assign to a non-existent array slot, circumventing the bounds checking present in the put method. To avoid this the size field should be private, with a public accessor method getsize() which allows size to be read, but not altered. b) The get method does not provide any bounds checking, so it is possible to attempt to read from a non-existent array slot. In older languages such as C this is entirely possible, so it would be essential to trap an out-of-bounds index in get. However Java does perform array bounds checking so this program will throw an exception if we try to read outside the array, giving us several choices. We could leave the code unaltered and rely on the caller to handle any resulting exceptions; we could catch the exception ourselves and rethrow it as a different kind of exception (the point of rethrowing is to give a more specific information to the caller - they shouldn t have to know the internals of our class in order to understand its error messages); or we can check the index in get and throw an Exception if the bounds are exceeded. This last option is probably the best. c) The put method performs bounds checking but if the index is out of bounds it silently fails. There are two alternative solutions: either throw an exception if put fails, or modify the method so that it returns a boolean indicting success or failure. This example is slightly artifical as Java provides safety checking for arrays as standard, but the same issues apply to more complicated classes: keep the class s internal state consistent, detect erronous usage and report failure effectively. 6. There are situations where we design classes which we would like to ensure are instantiated only once that is there is only ever one object of the class at any given time. Such a class is called a Singleton. a) Making use of the access modifiers, design a class which can be instantiated only once. (Hint: How will other programs gain access to the single instance of your class?) // has to be final otherwise subclasses could // override its Singleton-ness public final class Singleton { // the unique instance 5
6 private static Singleton singleton; // constructor is private so that it can only be seen // by this class private Singleton() { System.err.println("Singleton created!"); // create instance and ensure there is only one // static so not attached to any instance public static Singleton getinstance() { if(singleton == null) singleton = new Singleton(); return singleton; b) Can you think of any circumstances where you would want to use a Singleton class? Can you find any examples in the Java API? A non-trivial example is that of a resource pool. The ResourcePool object is responsible for creating and distributing objects which are expensive to create, such as database connections. The purpose of such a class would be defeated if an other class could just create new instance of it. Within the API java.lang.runtime is a Singleton. 7. List five common situations where an exception would be thrown. List the benefits of exceptions compared to traditional error handling. Can you think of a situation where traditional error handling would be problematic? Trying to derefence a null variable, array subscript out of bounds, file could not be opened, memory exhaustion, invalid method arguments. Among others: generally clearer better structured code; can handle errors non-locally; can group different types of error using subclasses of Exception; declaring which exceptions a method may throw is a form of documentation enforced by the compiler. An important example is within a constructor, where there is no return value. 8. Suppose that a program throws an exception and the appropriate exception handler begins executing. Suppose now that the exception handler itself throws an the same exception again. Does this create an infinite recursion? Explain your answer. No recusion will result since the exception handler is outside its own try block. Therefore the exception will be propagated up the call stack to be handled elsewhere. This can only happen finitely many times before the top of the call stack is reached and the Virtual Machine aborts. 6
7 9. For this question you should review material on Streams from CS1Ah Lecture Note 29. Consider the class shown below. import java.io.*; public class StringReader { public String[] strings; public StringReader(String filename, int size) { try { strings = new String[size]; FileInputStream file = new FileInputStream(filename); ObjectInputStream in = new ObjectInputStream(file); for(int i = 0 ; true ; i++) { Object o = in.readobject(); strings[i] = (String)o; catch(exception e) { // do nothing Can you identify the points in the file where an exception might be thrown? What type of Exeception could be thrown at each of those points? If an exception occured it would be caught at line 16. Do you think this a good idea? How would you improve it? Which of the possible exceptions do you think this class should attempt to deal with, and which should be passed up to the class s user? Line 9: FileNotFoundException. Line 9: SecurityException. Line 10: StreamCorruptedException. Line 10: IOException. Line 12: ClassNotFoundException Line 12: InvalidClassException Line 12: StreamCorruptedException Line 12: OptionalDataException Line 12: IOException Line 12: EOFException Line 13: ArrayIndexOutOfBoundsException Line 13: ClassCastException 7
8 From the above list we can see that the program might fail in a variety of ways, none of which we should blindly ignore. It would be unrealistic to catch all of these exceptions and handle then differently but there are a few we might want special treatment of. In particular, if nothing else goes wrong, one of EOFException and ArrayIndexOutOfBoundsException will always be thrown. We would probably want to handle these internally. Ross Duncan (with minor changes by Murray Cole), April 1st,
School 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 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 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 informationJava Primer. CITS2200 Data Structures and Algorithms. Topic 2
CITS2200 Data Structures and Algorithms Topic 2 Java Primer Review of Java basics Primitive vs Reference Types Classes and Objects Class Hierarchies Interfaces Exceptions Reading: Lambert and Osborne,
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 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 informationThe University of Melbourne Department of Computer Science and Software Engineering Software Design Semester 2, 2003
The University of Melbourne Department of Computer Science and Software Engineering 433-254 Software Design Semester 2, 2003 Answers for Tutorial 7 Week 8 1. What are exceptions and how are they handled
More 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 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 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 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 informationDefensive Programming
Defensive Programming Software Engineering CITS1220 Based on the Java1200 Lecture notes by Gordon Royle Lecture Outline Why program defensively? Encapsulation Access Restrictions Documentation Unchecked
More informationTopics. Java arrays. Definition. Data Structures and Information Systems Part 1: Data Structures. Lecture 3: Arrays (1)
Topics Data Structures and Information Systems Part 1: Data Structures Michele Zito Lecture 3: Arrays (1) Data structure definition: arrays. Java arrays creation access Primitive types and reference types
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 informationCS159. Nathan Sprague
CS159 Nathan Sprague What s wrong with the following code? 1 /* ************************************************** 2 * Return the maximum, or Integer. MIN_VALUE 3 * if the array has length 0. 4 ***************************************************
More informationErrors and Exceptions
Exceptions Errors and 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 isn t necessarily your fault trying
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 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 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 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 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 informationCS 11 java track: lecture 3
CS 11 java track: lecture 3 This week: documentation (javadoc) exception handling more on object-oriented programming (OOP) inheritance and polymorphism abstract classes and interfaces graphical user interfaces
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 informationChapter 4 Defining Classes I
Chapter 4 Defining Classes I This chapter introduces the idea that students can create their own classes and therefore their own objects. Introduced is the idea of methods and instance variables as the
More informationPages and 68 in [JN] conventions for using exceptions in Java. Chapter 8 in [EJ] guidelines for more effective use of exceptions.
CS511, HANDOUT 12, 7 February 2007 Exceptions READING: Chapter 4 in [PDJ] rationale for exceptions in general. Pages 56-63 and 68 in [JN] conventions for using exceptions in Java. Chapter 8 in [EJ] guidelines
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 informationGRAMMARS & PARSING. Lecture 7 CS2110 Fall 2013
1 GRAMMARS & PARSING Lecture 7 CS2110 Fall 2013 Pointers to the textbook 2 Parse trees: Text page 592 (23.34), Figure 23-31 Definition of Java Language, sometimes useful: http://docs.oracle.com/javase/specs/jls/se7/html/index.html
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 informationHere is a hierarchy of classes to deal with Input and Output streams.
PART 15 15. Files and I/O 15.1 Reading and Writing Files A stream can be defined as a sequence of data. The InputStream is used to read data from a source and the OutputStream is used for writing data
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 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 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 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 information16-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 informationContents. 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 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 informationVIRTUAL FUNCTIONS Chapter 10
1 VIRTUAL FUNCTIONS Chapter 10 OBJECTIVES Polymorphism in C++ Pointers to derived classes Important point on inheritance Introduction to virtual functions Virtual destructors More about virtual functions
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 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 informationDD2460 Software Safety and Security: Part III Exercises session 2: Type + Jif
DD2460 Software Safety and Security: Part III Exercises session 2: Type + Jif Gurvan Le Guernic adapted from Aslan Askarov DD2460 (III, E2) February 22 st, 2012 1 Noninterference type systems challenge
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 informationExceptions. 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 informationASSIGNMENT 5 Data Structures, Files, Exceptions, and To-Do Lists
ASSIGNMENT 5 Data Structures, Files, Exceptions, and To-Do Lists COMP-202B, Winter 2009, All Sections Due: Tuesday, April 14, 2009 (23:55) You MUST do this assignment individually and, unless otherwise
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 informationCS Internet programming Unit- I Part - A 1 Define Java. 2. What is a Class? 3. What is an Object? 4. What is an Instance?
CS6501 - Internet programming Unit- I Part - A 1 Define Java. Java is a programming language expressly designed for use in the distributed environment of the Internet. It was designed to have the "look
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 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 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 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 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 informationExceptions 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 informationCS 61B Discussion 5: Inheritance II Fall 2014
CS 61B Discussion 5: Inheritance II Fall 2014 1 WeirdList Below is a partial solution to the WeirdList problem from homework 3 showing only the most important lines. Part A. Complete the implementation
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. 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 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 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 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 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 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 informationCS11 Java. Fall Lecture 4
CS11 Java Fall 2014-2015 Lecture 4 Java File Objects! Java represents files with java.io.file class " Can represent either absolute or relative paths! Absolute paths start at the root directory of the
More informationException 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 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 informationException 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 informationMotivations. Chapter 12 Exceptions and File Input/Output
Chapter 12 Exceptions and File Input/Output CS1: Java Programming Colorado State University Motivations When a program runs into a runtime error, the program terminates abnormally. How can you handle the
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 informationPIC 20A Exceptions. Ernest Ryu UCLA Mathematics. Last edited: November 27, 2017
PIC 20A Exceptions Ernest Ryu UCLA Mathematics Last edited: November 27, 2017 Introductory example Imagine trying to read from a file. import java.io.*; public class Test { public static void main ( String
More informationChapter 12 Exception Handling and Text IO. Liang, Introduction to Java Programming, Tenth Edition, Global Edition. Pearson Education Limited
Chapter 12 Exception Handling and Text IO Liang, Introduction to Java Programming, Tenth Edition, Global Edition. Pearson Education Limited 2015 1 Motivations When a program runs into a runtime error,
More informationF I N A L E X A M I N A T I O N
Faculty Of Computer Studies M257 Putting Java to Work F I N A L E X A M I N A T I O N Number of Exam Pages: (including this cover sheet( Spring 2011 April 4, 2011 ( 5 ) Time Allowed: ( 1.5 ) Hours Student
More informationIntroduction to Programming Using Java (98-388)
Introduction to Programming Using Java (98-388) Understand Java fundamentals Describe the use of main in a Java application Signature of main, why it is static; how to consume an instance of your own class;
More informationExceptions. 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 informationExceptions. 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 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 informationJava in 21 minutes. Hello world. hello world. exceptions. basic data types. constructors. classes & objects I/O. program structure.
Java in 21 minutes hello world basic data types classes & objects program structure constructors garbage collection I/O exceptions Strings Hello world import java.io.*; public class hello { public static
More information15CS45 : OBJECT ORIENTED CONCEPTS
15CS45 : OBJECT ORIENTED CONCEPTS QUESTION BANK: What do you know about Java? What are the supported platforms by Java Programming Language? List any five features of Java? Why is Java Architectural Neutral?
More informationExceptions. 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 informationAbstract Classes, Exceptions
CISC 370: Inheritance, Abstract Classes, Exceptions June 15, 1 2006 1 Review Quizzes Grades on CPM Conventions Class names are capitalized Object names/variables are lower case String.doStuff dostuff();
More informationCS 112 Programming 2. Lecture 08. Exception Handling & Text I/O (1) Chapter 12 Exception Handling and Text IO
CS 112 Programming 2 Lecture 08 Exception Handling & Text I/O (1) Chapter 12 Exception Handling and Text IO rights reserved. 2 Motivation When a program runs into a runtime error, the program terminates
More informationCMSC 132: Object-Oriented Programming II
CMSC 132: Object-Oriented Programming II Java Support for OOP Department of Computer Science University of Maryland, College Park Object Oriented Programming (OOP) OO Principles Abstraction Encapsulation
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 informationCS 351 Design of Large Programs Singleton Pattern
CS 351 Design of Large Programs Singleton Pattern Brooke Chenoweth University of New Mexico Spring 2019 The Notion of a Singleton There are many objects we only need one of: Thread pools, caches, dialog
More informationJava How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.
Java How to Program, 10/e Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved. Data structures Collections of related data items. Discussed in depth in Chapters 16 21. Array objects Data
More informationAtelier Java - J1. Marwan Burelle. EPITA Première Année Cycle Ingénieur.
marwan.burelle@lse.epita.fr http://wiki-prog.kh405.net Plan 1 2 Plan 3 4 Plan 1 2 3 4 A Bit of History JAVA was created in 1991 by James Gosling of SUN. The first public implementation (v1.0) in 1995.
More informationGraphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub
Lebanese University Faculty of Science Computer Science BS Degree Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub 2 Crash Course in JAVA Classes A Java
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 informationFall 2017 CISC124 10/1/2017
CISC124 Today First onq quiz this week write in lab. More details in last Wednesday s lecture. Repeated: The quiz availability times will change to match each lab as the week progresses. Useful Java classes:
More informationCS 251 Intermediate Programming Methods and Classes
CS 251 Intermediate Programming Methods and Classes Brooke Chenoweth University of New Mexico Fall 2018 Methods An operation that can be performed on an object Has return type and parameters Method with
More informationCS 251 Intermediate Programming Methods and More
CS 251 Intermediate Programming Methods and More Brooke Chenoweth University of New Mexico Spring 2018 Methods An operation that can be performed on an object Has return type and parameters Method with
More informationUNIT 3 ARRAYS, RECURSION, AND COMPLEXITY CHAPTER 11 CLASSES CONTINUED
UNIT 3 ARRAYS, RECURSION, AND COMPLEXITY CHAPTER 11 CLASSES CONTINUED EXERCISE 11.1 1. static public final int DEFAULT_NUM_SCORES = 3; 2. Java allocates a separate set of memory cells in each instance
More informationIntroduction to Java. Handout-3a. cs402 - Spring
Introduction to Java Handout-3a cs402 - Spring 2003 1 Exceptions The purpose of exceptions How to cause an exception (implicitely or explicitly) How to handle ( catch ) an exception within the method where
More informationCS313D: ADVANCED PROGRAMMING LANGUAGE
CS313D: ADVANCED PROGRAMMING LANGUAGE Computer Science department Lecture 6 : Abstraction Lecture Contents 2 Abstract classes Abstract methods Case study: Polymorphic processing Sealed methods & classes
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 informationDOWNLOAD PDF CORE JAVA APTITUDE QUESTIONS AND ANSWERS
Chapter 1 : Chapter-wise Java Multiple Choice Questions and Answers Interview MCQs Java Programming questions and answers with explanation for interview, competitive examination and entrance test. Fully
More informationTwo Key JDK 10 Features
Supplement to Java: The Complete Reference, Tenth Edition Two Key JDK 10 Features This supplement to Java: The Complete Reference, Tenth Edition discusses two key features added by JDK 10. It is provided
More informationCOP 3330 Final Exam Review
COP 3330 Final Exam Review I. The Basics (Chapters 2, 5, 6) a. comments b. identifiers, reserved words c. white space d. compilers vs. interpreters e. syntax, semantics f. errors i. syntax ii. run-time
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 informationCS260 Intro to Java & Android 03.Java Language Basics
03.Java Language Basics http://www.tutorialspoint.com/java/index.htm CS260 - Intro to Java & Android 1 What is the distinction between fields and variables? Java has the following kinds of variables: Instance
More informationExceptions. CS162: Introduction to Computer Science II. Exceptions. Exceptions. Exceptions. Exceptions. Exceptions
CS162: Introduction to Computer Science II A typical way to handle error conditions is through the return value. For example, suppose we create a loadfile() function that returns true if it loaded the
More informationCompaq Interview Questions And Answers
Part A: Q1. What are the difference between java and C++? Java adopts byte code whereas C++ does not C++ supports destructor whereas java does not support. Multiple inheritance possible in C++ but not
More informationEXCEPTIONS. 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 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 information