Unit IV Generic Programming

Size: px
Start display at page:

Download "Unit IV Generic Programming"

Transcription

1 Unit IV Generic Programming Generics are a facility of generic programming that was added to the Java programming language. Generic programming is a style of computer programming in which algorithms are written in terms of to-be-specified-later types that are then instantiated when needed for specific types provided as parameters. As per Java Language Specification: A type variable is an unqualified identifier. Type variables are introduced by generic class declarations, generic interface declarations, generic method declarations, and by generic constructor declarations. A class is generic if it declares one or more type variables. These type variables are known as the type parameters of the class. It defines one or more type variables that act as parameters. A generic class declaration defines a set of parameterized types, one for each possible invocation of the type parameter section. All of these parameterized types share the same class at runtime. An interface is generic if it declares one or more type variables. These type variables are known as the type parameters of the interface. It defines one or more type variables that act as parameters. A generic interface declaration defines a set of types, one for each possible invocation of the type parameter section. All parameterized types share the same interface at runtime. A method is generic if it declares one or more type variables. These type variables are known as the formal type parameters of the method. The form of the formal type parameter list is identical to a type parameter list of a class or interface. A constructor can be declared as generic, independently of whether the class the constructor is declared in is itself generic. A constructor is generic if it declares one or more type variables. These type variables are known as the formal type parameters of the constructor. The form of the formal type parameter list is identical to a type parameter list of a generic class or interface. Motivation for Generics: Overloaded methods are often used to perform similar operations on different types of data. To motivate generic methods, let s begin with an example that contains three overloaded printarray methods. These methods print the string representations of the elements of an Integer array, a Double array and a Character array, respectively. Note that we could have used arrays of primitive types int, double and char in this example. We chose to use arrays of typeinteger, Double and Character to

2 set up our generic method example, because only reference types can be used with generic methods and classes.

3 } // end main } // end class Overloaded Methods Output: Array integerarray contains: Array doublearray contains: Array characterarray contains: H E L L O Generic class definitions Here is an example of a generic class: This generic class can be used in the following way:

4 Type erasure Generics are checked at compile-time for type correctness. The generic type information is then removed via a process called type erasure. For example, List<Integer> will be converted to the raw type (non-generic type) List, which can contain arbitrary objects. However, due to the compile-time check, the resulting code is guaranteed to be type correct, as long as the code generated no unchecked compiler warnings. As a result, there is no way to tell at runtime which type parameter is used on an object. For example, when you examine an ArrayList at runtime, there is no general way to tell whether it was an ArrayList<Integer> or an ArrayList<Float>. The exception to this is by using Reflection on existing list elements. However, if the list is empty or if its elements are subtypes of the parameterized type, even Reflection will not divulge the parameterized type. The following code demonstrates that the Class objects appear the same. The following code demonstrates that the Class objects appear the same. ArrayList<Integer> li = new ArrayList<Integer>(); ArrayList<Float> lf = new ArrayList<Float>(); if (li.getclass() == lf.getclass()) // evaluates to true System.out.println("Equal"); Java generics differ from C++ templates. Java generics generate only one compiled version of a generic class or function regardless of the number of types used. Furthermore, the Java compiler does not need to know which parameterized type is used because the type information is validated at compile-time and erased from the compiled code. Consequently, one cannot instantiate a Java class of a parameterized type because instantiation requires a call to a constructor, which is not possible when the type is unknown at both compile-time and runtime. T instantiateelementtype(list<t> arg){ return new T(); //causes a compile error} Because there is only one copy of a generic class, static variables are shared among all the instances of the class, regardless of their type parameter. As a result, the type parameter cannot be used in the declaration of static variables or in static methods.

5 Static variables and static methods are "outside" of the scope of the class's parameterized types. Generic methods: Generic Methods - Genericity is not limited to classes and interfaces, you can define generic methods. Static methods, nonstatic methods, and constructors can all be parameterized in almost the same way as for classes and interfaces, but the syntax is a bit different. Generic methods are also invoked in the same way as non-generic methods. Before we see an example of a generics method, consider the following segment of code that prints out all the elements in a collection: public void printcollection(collection c) { Iterator i = c.iterator(); for(int k = 0;k<c.size();k++) { System.out.println(i.next()); } } Using generics, this can be re-written as follows. Note that the Collection<?> is the collection of an unknown type. void printcollection(collection<?> c) { for(object o:c) { System.out.println(o); } } Example:

6 Bounded Type Parameters: There may be times when you'll want to restrict the kinds of types that are allowed to be passed to a type parameter. For example, a method that operates on numbers might only want to accept instances of Number or its subclasses. This is what bounded type parameters are for. To declare a bounded type parameter, list the type parameter's name, followed by the extends keyword, followed by its upper bound, which in this example is Number. Note that, in this context, extends is used in a general sense to mean either "extends" (as in classes) or "implements" (as in interfaces).

7 By modifying our generic method to include this bounded type parameter, compilation will now fail, since our invocation of inspect still includes a String: To specify additional interfaces that must be implemented, use the & character, as in: Exceptions: Exceptions are such anomalous conditions (or typically an event) which changes the normal flow of execution of a program. Exceptions are used for signaling erroneous (exceptional) conditions which occur during the run time processing. Exceptions may occur in any programming language. Occurrence of any kind of exception in java applications may result in an abrupt termination of the JVM or simply the JVM crashes which leaves the user unaware of the causes of such anomalous conditions. However Java provides mechanisms to handle such situations through its superb exception handling mechanism. The Java programming language uses Exception classes to handle such erroneous conditions and exceptional events. Exception Hierarchy: There are three types of Exceptions: 1. Checked Exceptions - These are the exceptions which occur during the compile time of the program. The compiler checks at the compile time that whether the program contains handlers for checked exceptions or not. These exceptions do not extend

8 RuntimeException class and must be handled to avoid a compile-time error by the programmer. These exceptions extend the java.lang.exception class. These exceptional conditions should be anticipated and recovered by an application. Furthermore checked exceptions are required to be caught. Remember that all the exceptions are checked exceptions unless and until those indicated by Error, RuntimeException or their subclasses. For example: If you call the readline() method on a BufferedReader object then the IOException may occur or if you want to build a program that could read a file with a specific name then you would be prompted to input a file name by the application. Then it passes the name to the constructor for java.io.filereader and opens the file. However if you do not provide the name of any existing file then the constructor throwsjava.io.filenotfoundexception which abrupt the application to succeed. Hence this exception will be caught by a well-written application and will also prompt to correct the file name. Here is the list of checked exceptions: NoSuchFieldException InstantiationException IllegalAccessException ClassNotFoundException NoSuchMethodException CloneNotSupportedException InterruptedException 2. Unchecked Exceptions - Unchecked exceptions are the exceptions which occur during the runtime of the program. Unchecked exceptions are internal to the application and extend the java.lang.runtimeexception that is inherited from java.lang.exceptionclass. These exceptions cannot be anticipated and recovered like programming bugs, such as logic errors or improper use of an API. These type of exceptions are also calledruntime exceptions that are usually caused by data errors, like arithmetic overflow, divide by zero etc. Let s take the same file name example as described earlier. In that example the file name is passed to the constructor for FileReader. However, the constructor will throw NullPointerException if a logic error causes a null to be passed to the constructor. Well in this case the exception could be caught by the application but it would rather try to eliminate the bug due to which the exception has occurred. You must have encountered the most common exception in your program i.e. the ArithmeticException. I am sure you must be familiar with the reason of its occurrence that is when something tries to divide by zero. Similarly when an instance data member or method of a reference variable is to be accessed that hasn't yet referenced an object throws NullPointerException. Here is the list of unchecked exceptions.

9 IndexOutOfBoundsException ArrayIndexOutOfBoundsException ClassCastException ArithmeticException NullPointerException IllegalStateException SecurityException 3. Error - The errors in java are external to the application. These are the exceptional conditions that could not be usually anticipated by the application and also could not be recovered from. Error exceptions belong to Error and its subclasses are not subject to the catch or Specify requirement. Suppose a file is successfully opened by an application for input but due to some system malfunction could not be able to read that file then the java.io.ioerror would be thrown. This error will cause the program to terminate but if an application wants then the error might be caught. An Error indicates serious problems that a reasonable application should not try to catch. Most such errors are abnormal conditions. Hence we conclude that Errors and runtime exceptions are together called as unchecked exceptions. Throwing Exceptions - If a method needs to be able to throw an exception, it has to declare the exception(s) thrown in the method signature, and then include a throwstatement in the method. Here is an example: When an exception is thrown the method stops execution right after the "throw" statement. Any statements following the "throw" statement are not executed. In the example above the "return numbertodivide / numbertodivideby;" statement is not executed if a BadNumberException is thrown. The program resumes execution when the exception is caught somewhere by a "catch" block. Catching exceptions is explained later. You can throw any type of exception from your code, as long as your method signature declares it. You can also make up your own exceptions. Exceptions are regular Java classes that extends java.lang.exception, or any of the other built-in exception classes. If a method declares that it throws an exception A, then it is also legal to throw subclasses of A.

10 Catching Exceptions - If a method calls another method that throws checked exceptions, the calling method is forced to either pass the exception on, or catch it. Catching the exception is done using a try-catch block. Here is an example: The BadNumberException parameter is inside the catch-clause points to the exception thrown from the divide method, if an exception is thrown. If no exeception is thrown by any of the methods called or statements executed inside the try-block, the catch-block is simply ignored. It will not be executed. If an exception is thrown inside the try-block, for instance from the divide method, the program flow of the calling method, calldivide, is interrupted just like the program flow inside divide. The program flow resumes at a catch-block in the call stack that can catch the thrown exception. In the example above the "System.out.println(result);" statement will not get executed if an exception is thrown fromt the divide method. Instead program execution will resume inside the "catch (BadNumberException e) { }" block. If an exception is thrown inside the catch-block and that exception is not caught, the catch-block is interrupted just like the try-block would have been. When the catch block is finished the program continues with any statements following the catch block. In the example above the "System.out.println("Division attempt done");" statement will always get executed. Propagating Exceptions: You don't have to catch exceptions thrown from other methods. If you cannot do anything about the exception where the method throwing it is called, you can just let the method propagate the exception up the call stack to the method that called this method. If you do so the method calling the method that throws the exception must also declare to throw the exception. Here is how the calldivide() method would look in that case.

11 Notice how the try-catch block is gone, and the calldivide method now declares that it can throw a BadNumberException. The program execution is still interrupted if an exception is thrown from the divide method. Thus the "System.out.println(result);" method will not get executed if an exception is thrown from the divide method. But now the program execution is not resumed inside the calldivide method. The exception is propagated to the method that calls calldivide. Program execution doesn't resume until a catch-block somewhere in the call stack catches the exception. All methods in the call stack between the method throwing the exception and the method catching it have their execution stopped at the point in the code where the exception is thrown or propagated. Example: Catching IOException's If an exception is thrown during a sequence of statements inside a try-catch block, the sequence of statements is interrupted and the flow of control will skip directly to the catch-block. This code can be interrupted by exceptions in several places: If the reader.read() method call throws an IOException, the following System.out.println((char) i ); is not executed. Neither is the last reader.close() or the

12 System.out.println("--- File End ---"); statements. Instead the program skips directly to the catch(ioexception e){... } catch clause. If the new FileReader("someFile"); constructor call throws an exception, none of the code inside the try-block is executed. Example: Propagating IOException's This code is a version of the previous method that throws the exceptions instead of catching them: If an exception is thrown from the reader.read() method then program execution is halted, and the exception is passed up the call stack to the method that called openfile(). If the calling method has a try-catch block, the exception will be caught there. If the calling method also just throws the method on, the calling method is also interrupted at the openfile() method call, and the exception passed on up the call stack. The exception is propagated up the call stack like this until some method catches the exception, or the Java Virtual Machine does. Finally You can attach a finally-clause to a try-catch block. The code inside the finally clause will always be executed, even if an exception is thrown from within the try or catch block. If your code has a return statement inside the try or catch block, the code inside the finally-block will get executed before returning from the method. Here is how a finally clause looks:

13 No matter whether an exception is thrown or not inside the try or catch block the code inside the finally-block is executed. The example above shows how the file reader is always closed, regardless of the program flow inside the try or catch block. Note: If an exception is thrown inside a finally block, and it is not caught, then that finally block is interrupted just like the try-block and catch-block is. That is why the previous example had the reader.close() method call in the finally block wrapped in a trycatch block: That way the System.out.println("--- File End ---"); method call will always be executed. If no unchecked exceptions are thrown that is. More about checked and unchecked in a later chapter. You don't need both a catch and a finally block. You can have one of them or both of them with a try-block, but not any of them. This code doesn't catch the exception but lets it propagate up the call stack. Due to the finally block the code still closes the filer reader even if an exception is thrown.

14 Logging: The JDK contains the "Java Logging API". Via a logger you can save text to a central place to report on errors, provide additional information about your program, etc. This logging API allows to configure how messages are written by which class with which priority Overview of Control Flow: Applications make logging calls on Logger objects. Loggers are organized in a hierarchical namespace and child Loggers may inherit some logging properties from their parents in the namespace. Applications make logging calls on Logger objects. These Logger objects allocate LogRecord objects which are passed to Handler objects for publication. Both Loggers and Handlers may use logging Levels and (optionally) Filters to decide if they are interested in a particular LogRecord. When it is necessary to publish a LogRecord externally, a Handler can (optionally) use a Formatter to localize and format the message before publishing it to an I/O stream.

15 Each Logger keeps track of a set of output Handlers. By default all Loggers also send their output to their parent Logger. But Loggers may also be configured to ignore Handlers higher up the tree. Some Handlers may direct output to other Handlers. For example, the MemoryHandler maintains an internal ring buffer of LogRecords and on trigger events it publishes its LogRecords through a target Handler. In such cases, any formatting is done by the last Handler in the chain. The APIs are structured so that calls on the Logger APIs can be cheap when logging is disabled. If logging is disabled for a given log level, then the Logger can make a cheap comparison test and return. If logging is enabled for a given log level, the Logger is still careful to minimize costs before passing the LogRecord into the Handlers. In particular, localization and formatting (which are relatively expensive) are deferred until the Handler requests them. For example, a MemoryHandler can maintain a circular buffer of LogRecords without having to pay formatting costs. Log Levels: Each log message has an associated log Level. The Level gives a rough guide to the importance and urgency of a log message. Log level objects encapsulate an integer value, with higher values indicating higher priorities. The Level class defines seven standard log levels, ranging from FINEST (the lowest priority, with the lowest value) to SEVERE (the highest priority, with the highest value). Loggers: As stated earlier, client code sends log requests to Logger objects. Each logger keeps track of a log level that it is interested in, and discards log requests that are below this level. Loggers are normally named entities, using dot-separated names such as "java.awt". The namespace is hierarchical and is managed by the LogManager. The namespace should typically be aligned with the Java packaging namespace, but is not required to follow it slavishly. For example, a Logger called "java.awt" might handle logging requests for classes in the java.awt package, but it might also handle logging for classes in sun.awt that support the client-visible abstractions defined in the java.awt package.

16 In addition to named Loggers, it is also possible to create anonymous Loggers that don't appear in the shared namespace. See section Loggers keep track of their parent loggers in the logging namespace. A logger's parent is its nearest extant ancestor in the logging namespace. The root Logger (named "") has no parent. Anonymous loggers are all given the root logger as their parent. Loggers may inherit various attributes from their parents in the logger namespace. In particular, a logger may inherit: Logging level. If a Logger's level is set to be null then the Logger will use an effective Level that will be obtained by walking up the parent tree and using the first non-null Level. Handlers. By default a Logger will log any output messages to its parent's handlers, and so on recursively up the tree. Resource bundle names. If a logger has a null resource bundle name, then it will inherit any resource bundle name defined for its parent, and so on recursively up the tree. Logging Methods: The Logger class provides a large set of convenience methods for generating log messages. For convenience, there are methods for each logging level, named after the logging level name. Thus rather than calling "logger.log(constants.warning,..." a developer can simply call the convenience method "logger.warning)..." There are two different styles of logging methods, to meet the needs of different communities of users. First, there are methods that take an explicit source class name and source method name. These methods are intended for developers who want to be able to quickly locate the source of any given logging message. An example of this style is: Second, there are a set of methods that do not take explicit source class or source method names. These are intended for developers who want easy-to-use logging and do not require detailed source information. For this second set of methods, the Logging framework will make a "best effort" to determine which class and method called into the logging framework and will add this information into the LogRecord. However, it is important to realize that this automatically inferred information may only be approximate. The latest generation of virtual machines perform extensive optimizations when JITing and may entirely remove stack frames, making it impossible to reliably locate the calling class and method. Handlers

17 J2SE provides the following Handlers: StreamHandler: A simple handler for writing formatted records to an OutputStream. ConsoleHandler: A simple handler for writing formatted records to System.err FileHandler: A handler that writes formatted log records either to a single file, or to a set of rotating log files. SocketHandler: A handler that writes formatted log records to remote TCP ports. MemoryHandler: A handler that buffers log records in memory. It is fairly straightforward to develop new Handlers. Developers requiring specific functionality can either develop a Handler from scratch or subclass one of the provided Handlers. Formatters J2SE also includes two standard Formatters: SimpleFormatter: Writes brief "human-readable" summaries of log records. XMLFormatter: Writes detailed XML-structured information. As with Handlers, it is fairly straightforward to develop new Formatters. The LogManager There is a global LogManager object that keeps track of global logging information. This includes: A hierarchical namespace of named Loggers. A set of logging control properties read from the configuration file. There is a single LogManager object that can be retrieved using the static LogManager.getLogManager method. This is created during LogManager initialization, based on a system property. This property allows container applications (such as EJB containers) to substitute their own subclass of LogManager in place of the default class. Create a logger The package java.util.logging provides the logging capabilities via the class Logger. To create a logger in your Java coding. import java.util.logging.logger; private final static Logger LOGGER = Logger.getLogger(MyClass.class.getName()); Level The log levels define the severity of a message. The class Level is used to define which messages should be written to the log. Die Log Levels in descending order are: SEVERE (highest) WARNING INFO

18 CONFIG FINE FINER FINEST In addition to that you have also the levels OFF and ALL to turn the logging of or to log everything. For example the following will set the logger to level info which means all messages with severe, warning and info will be logged. LOGGER.setLevel(Level.INFO); An Example: To help motivate the use of the logging API, we will use a simple program, based on the idea of a "Hello World" program. We will expand upon this simple program in order to demonstrate and motivate the logging API. The first thing we will do is actually generate a logging message. This is straightforward; we need to create a Logger object, which represents thehelloworld class, like this:

19 This generates a Logger, which we can use to generate logging messages. Since you typically use one logger per class, we can make it a static field of the HelloWorld class. We use the fully qualified name of the HelloWorld class as the name of thelogger. We'll look at the reasons for this in more detail later. Now, let's actually use the Logger to try to generate a logging message:

20 The logging API has a configuration file and by default, it provides a handler that will send logging messages, in the form of alogrecord to the console (System.err). So we would expect to see the string "Hello logging!"; appear before our message of "Hello world!". But if you run this program you only see "Hello world!": What's going on here? The answer lies in the notion of logging levels. Assertions - An assertion has a Boolean expression that, if evaluated as false, indicates a bug in the code. This mechanism provides a way to detect when a program starts falling into an inconsistent state. Assertions are excellent for documenting assumptions and invariants about a class. Here is a simple example of assertion: This asserts that acct is not null. If acct is null, an AssertionError is thrown. Any line that executes after the assert statement can safely assume that acct is not null. Using assertions helps developers write code that is more correct, more readable, and easier to maintain. Thus, assertions improve the odds that the behavior of a class matches the expectations of its clients. Note that assertions can be compiled out. In languages such as C/C++, this means using the preprocessor. In C/C++, you can use assertions through the assert macro, which has the following definition in ANSI C: void assert(int expression) The program will be aborted if the expression evaluates to false, and it has no effect if the expression evaluates to true. When testing and debugging is completed, assertions do not have to be removed from the program. However, note that the program will be larger in size and therefore slower to load. When assertions are no longer needed, the line #define NDEBUG is inserted at the beginning of the program. This causes the C/C++ preprocessor to ignore all assertions, instead of deleting them manually. In other words, this is a requirement for performance reasons. You should write assertions into software in a form that can be optionally compiled. Thus, assertions should be executed with the code only when you are debugging your program -- that is, when assertions will really help flush out errors.

21 You can think of assertions as a uniform mechanism that replaces the use of ad hoc conditional tests. Implementing Assertions in Java Technology J2SE 1.3 and earlier versions have no built-in support for assertions. They can, however, be provided as an ad hoc solution. Here is an example of how you would roll your own assertion class. Here we have an assert method that checks whether a Boolean expression is true or false. If the expression evaluates to true, then there is no effect. But if it evaluates to false, the assert method prints the stack trace and the program aborts. In this sample implementation, a second argument for a string is used so that the cause of error can be printed. Note that in the assert method, I am checking whether the value of NDEBUG is on (true) or off (false). If NDEBUG sets to true, then the assertion is to be executed. Otherwise, it would have no effect. The user of this class is able to set assertions on or off by toggling the value of NDEBUG. Code Sample 1 shows my implementation. } } Note: In order for Code Sample 1 to compile, use -source 1.3 because assert is a keyword as of J2SE 1.4. Otherwise, you will get the following error message:

22 Code Sample 2 demonstrates how to use the Assertion class. In this example, an integer representing the user's age is read. If the age is greater than or equal to 18, the assertion evaluates to true, and it will have no effect on the program execution. But if the age is less than 18, the assertion evaluates to false. The program then aborts, displays the message You are too young to vote, and shows the stack trace. It is important to note that in this example assertions are used to validate user input and that no invariant is being tested or verified. This is merely to demonstrate the use of assertions.

23 In the three examples, if you do not want assertions to be executed as part of the code, uncomment the line Assert.NDEBUG = false; Using Assertions: Use the assert statement to insert assertions at particular points in the code. The assert statement can have one of two forms: The errormessage is an optional string message that would be shown when an assertion fails. As an example, I will modify Code Sample 3 to use the assert statement instead of my Assertion class, as shown in Code Sample 4. If you try to compile your assertion-enabled classes without using the -source 1.4 option, you will get a compiler error saying that assert is a new keyword as of release 1.4. If you now run the program using the command prompt> java AssertionTest3

24 and you enter a valid character, it will work fine. However, if you enter an invalid character, nothing will happen. This is because, by default, assertions are disabled at runtime. To enable assertions, use the switch -enableassertion (or -ea) as follows: Following is a sample run: When an assertion fails, it means that the application has entered an incorrect state. Possible behaviors may include suspending the program or allowing it to continue to run. A good behavior, however, might be to terminate the application, because it may start functioning inappropriately after a failure. In this case, when an assertion fails, an AssertionError is thrown. Note: By default, assertions are disabled, so you must not assume that the Boolean expression contained in an assertion will be evaluated. Therefore, your expressions must be free of side effects. The switch -disableassertion (or -da) can be used to disable assertions. This, however, is most useful when you wish to disable assertions on classes from specific packages. For example, to run the program MyClass with assertions disabled in class Hello, you can use the following command: And to disable assertions in a specific package and any subpackages it may have, you can use the following command: Note that the three-dot ellipsis (...) is part of the syntax. Switches can be combined. For example, to run a program with assertions enabled in the com.javacourses.tests package (and any subpackages) and disabled in the class com.javacourses.ui.phone, you can use the following command: Note that when switches are combined and applied to packages, they are applied to all classes, including system classes (which do not have class loaders). But if you use them with no arguments (-ea or -da), they do not apply to system classes. In other words, if you use the command

25 then assertions are enabled in all classes except system classes. If you wish to turn assertions on or off in system classes, use the switches -enablesystemassertions (or -esa) and -disablesystemassertions (or -dsa). Using Assertions for Design by Contract - The assertion facility can help you in supporting an informal design-by-contract style of programming. We will now see examples of using assertions for preconditions, postconditions, and class invariants. The examples are snippets of code from an integer stack, which provides operations such as push to add an item on the stack and pop to retrieve an item from the stack. Preconditions - In order to retrieve an item from the stack, the stack must not be empty. The condition that the stack must not be empty is a precondition. This precondition can be programmed using assertions as follows: } Note: Because assertions might be disabled in some cases, precondition checking can still be performed by checks inside methods that result in exceptions such Postconditions - In order to push an item on the stack, the stack must not be full. This is a precondition. To add an item on the stack, we assign the element to be added to the next index in the stack as follows: However, if you make a mistake and you write this statement as then you have a bug. In this case, we need to ensure that invoking the push operation is working correctly. So the postcondition here is to ensure that the new index in the stack is the old index plus one. Also, we need to make sure that the element has been added on the stack. The following snippet of code shows the push operation with a precondition and a postcondition.

26 Note that if a method has multiple return statements, then postconditions should be evaluated before each of these return statements. Class Invariants: A class invariant is a predicate that must be true before and after any method completes. In the stack example, the invariant would be that the number of elements in the stack is greater than or equal to zero and the number of elements should not exceed the maximum capacity of the class. These conditions, for example, can be coded as follows: To check that the stack should satisfy this predicate at all times, each public method and constructor should contain the assertion right before each return.

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

QUESTION BANK. SUBJECT CODE / Name: CS2311 OBJECT ORIENTED PROGRAMMING

QUESTION BANK. SUBJECT CODE / Name: CS2311 OBJECT ORIENTED PROGRAMMING QUESTION BANK DEPARTMENT:EEE SEMESTER: V SUBJECT CODE / Name: CS2311 OBJECT ORIENTED PROGRAMMING UNIT V PART - A (2 Marks) 1. What is the difference between super class and sub class? (AUC MAY 2013) The

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

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

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

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

Here is a hierarchy of classes to deal with Input and Output streams.

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

Programming II (CS300)

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

More information

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

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

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

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

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

More information

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

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

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

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

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

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

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

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

Pages and 68 in [JN] conventions for using exceptions in Java. Chapter 8 in [EJ] guidelines for more effective use of exceptions.

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

1 Shyam sir JAVA Notes

1 Shyam sir JAVA Notes 1 Shyam sir JAVA Notes 1. What is the most important feature of Java? Java is a platform independent language. 2. What do you mean by platform independence? Platform independence means that we can write

More information

CS112 Lecture: Exceptions and Assertions

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

More information

Program Correctness and Efficiency. Chapter 2

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

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

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

More information

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

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

More information

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

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

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

More information

Exception Handling Introduction. Error-Prevention Tip 13.1 OBJECTIVES

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

More information

Lecture 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

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

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

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

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

More information

Semantic Analysis. CSE 307 Principles of Programming Languages Stony Brook University

Semantic Analysis. CSE 307 Principles of Programming Languages Stony Brook University Semantic Analysis CSE 307 Principles of Programming Languages Stony Brook University http://www.cs.stonybrook.edu/~cse307 1 Role of Semantic Analysis Syntax vs. Semantics: syntax concerns the form of a

More information

Today. Instance Method Dispatch. Instance Method Dispatch. Instance Method Dispatch 11/29/11. today. last time

Today. Instance Method Dispatch. Instance Method Dispatch. Instance Method Dispatch 11/29/11. today. last time CS2110 Fall 2011 Lecture 25 Java program last time Java compiler Java bytecode (.class files) Compile for platform with JIT Interpret with JVM Under the Hood: The Java Virtual Machine, Part II 1 run native

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

Introduction Unit 4: Input, output and exceptions

Introduction 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

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 Exceptions Lecture 11 Fall 2005

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

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

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

School of Informatics, University of Edinburgh

School of Informatics, University of Edinburgh 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

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

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

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

Casting -Allows a narrowing assignment by asking the Java compiler to "trust us"

Casting -Allows a narrowing assignment by asking the Java compiler to trust us Primitives Integral types: int, short, long, char, byte Floating point types: double, float Boolean types: boolean -passed by value (copied when returned or passed as actual parameters) Arithmetic Operators:

More information

CS 315 Software Design Homework 3 Preconditions, Postconditions, Invariants Due: Sept. 29, 11:30 PM

CS 315 Software Design Homework 3 Preconditions, Postconditions, Invariants Due: Sept. 29, 11:30 PM CS 315 Software Design Homework 3 Preconditions, Postconditions, Invariants Due: Sept. 29, 11:30 PM Objectives Defining a wellformed method to check class invariants Using assert statements to check preconditions,

More information

COP 3330 Final Exam Review

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

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

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

More information

Checked and Unchecked Exceptions in Java

Checked and Unchecked Exceptions in Java Checked and Unchecked Exceptions in Java Introduction In this article from my free Java 8 course, I will introduce you to Checked and Unchecked Exceptions in Java. Handling exceptions is the process by

More information

Java Logging APIs. Abstract. This is the Public Review draft of the Java Logging APIs proposed in JSR-047.

Java Logging APIs. Abstract. This is the Public Review draft of the Java Logging APIs proposed in JSR-047. Java Logging APIs Abstract This is the Public Review draft of the Java Logging APIs proposed in JSR-047. There are change bars relative to the Community Review draft (0.50). There is a change history on

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

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

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

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

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

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

Introduction to Programming Using Java (98-388)

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

CSC 1214: Object-Oriented Programming

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

More information

DOWNLOAD PDF CORE JAVA APTITUDE QUESTIONS AND ANSWERS

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

Chapter 14. Exception Handling and Event Handling

Chapter 14. Exception Handling and Event Handling Chapter 14 Exception Handling and Event Handling Chapter 14 Topics Introduction to Exception Handling Exception Handling in Ada Exception Handling in C++ Exception Handling in Java Introduction to Event

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

Programming Languages and Techniques (CIS120)

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

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.

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

Unit 5 - Exception Handling & Multithreaded

Unit 5 - Exception Handling & Multithreaded Exceptions Handling An exception (or exceptional event) is a problem that arises during the execution of a program. When an Exception occurs the normal flow of the program is disrupted and the program/application

More information

Lab 5: Java IO 12:00 PM, Feb 21, 2018

Lab 5: Java IO 12:00 PM, Feb 21, 2018 CS18 Integrated Introduction to Computer Science Fisler, Nelson Contents Lab 5: Java IO 12:00 PM, Feb 21, 2018 1 The Java IO Library 1 2 Program Arguments 2 3 Readers, Writers, and Buffers 2 3.1 Buffering

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

Chapter 13 Exception Handling

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

More information

14. Exception Handling

14. Exception Handling 14. Exception Handling 14.1 Intro to Exception Handling In a language without exception handling When an exception occurs, control goes to the operating system, where a message is displayed and the program

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

Course Status Polymorphism Containers Exceptions Midterm Review. CS Java. Introduction to Java. Andy Mroczkowski

Course Status Polymorphism Containers Exceptions Midterm Review. CS Java. Introduction to Java. Andy Mroczkowski CS 190 - Java Introduction to Java Andy Mroczkowski uamroczk@cs.drexel.edu Department of Computer Science Drexel University February 11, 2008 / Lecture 4 Outline Course Status Course Information & Schedule

More information

Object Oriented Programming

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

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

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

More information

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

Announcements. Java Graphics. Exceptions. Java Odds & Ends

Announcements. Java Graphics. Exceptions. Java Odds & Ends Java Odds & Ends Lecture 25 CS211 Fall 2005 Final Exam Wednesday, 12/14 9:00-11:30am Uris Aud Review Session Sunday, 12/11 1:00-2:30pm Kimball B11 Check your final exam schedule! Announcements For exam

More information

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

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

Assertions, pre/postconditions

Assertions, pre/postconditions Programming as a contract Assertions, pre/postconditions Assertions: Section 4.2 in Savitch (p. 239) Specifying what each method does q Specify it in a comment before method's header Precondition q What

More information

Designing Robust Classes

Designing 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

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

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

엄현상 (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

Motivations. Chapter 12 Exceptions and File Input/Output

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

CS2110 Fall 2011 Lecture 25. Under the Hood: The Java Virtual Machine, Part II

CS2110 Fall 2011 Lecture 25. Under the Hood: The Java Virtual Machine, Part II CS2110 Fall 2011 Lecture 25 Under the Hood: The Java Virtual Machine, Part II 1 Java program last time Java compiler Java bytecode (.class files) Compile for platform with JIT Interpret with JVM run native

More information

CS11 Advanced Java. Winter Lecture 2

CS11 Advanced Java. Winter Lecture 2 CS11 Advanced Java Winter 2011-2012 Lecture 2 Today s Topics n Assertions n Java 1.5 Annotations n Classpaths n Unit Testing! n Lab 2 hints J Assertions! n Assertions are a very useful language feature

More information

Chapter 4 Defining Classes I

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

Java Errors and Exceptions. Because Murphy s Law never fails

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

More information

Core Java Interview Questions and Answers.

Core Java Interview Questions and Answers. Core Java Interview Questions and Answers. Q: What is the difference between an Interface and an Abstract class? A: An abstract class can have instance methods that implement a default behavior. An Interface

More information

CS 231 Data Structures and Algorithms, Fall 2016

CS 231 Data Structures and Algorithms, Fall 2016 CS 231 Data Structures and Algorithms, Fall 2016 Dr. Bruce A. Maxwell Department of Computer Science Colby College Course Description Focuses on the common structures used to store data and the standard

More information

CS 221 Review. Mason Vail

CS 221 Review. Mason Vail CS 221 Review Mason Vail Inheritance (1) Every class - except the Object class - directly inherits from one parent class. Object is the only class with no parent. If a class does not declare a parent using

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

WA1278 Introduction to Java Using Eclipse

WA1278 Introduction to Java Using Eclipse Lincoln Land Community College Capital City Training Center 130 West Mason Springfield, IL 62702 217-782-7436 www.llcc.edu/cctc WA1278 Introduction to Java Using Eclipse This course introduces the Java

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

School of Informatics, University of Edinburgh

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 information