Exceptions, Interfaces & Generics

Slides:



Advertisements
Similar presentations
METHOD OVERRIDING 1.Sub class can override the methods defined by the super class. 2.Overridden Methods in the sub classes should have same name, same.
Advertisements

CS102--Object Oriented Programming
Introduction to Exceptions in Java. 2 Runtime Errors What are syntax errors? What are runtime errors? Java differentiates between runtime errors and exceptions.
Exceptions and Exception Handling Carl Alphonce CSE116 March 9, 2007.
Exceptions Any number of exceptional circumstances may arise during program execution that cause trouble import java.io.*; class IOExample { public static.
Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.
Lecture 28 More on Exceptions COMP1681 / SE15 Introduction to Programming.
Exceptions and Exception Handling (2) Carl Alphonce CSE116.
CSM-Java Programming-I Spring,2005 Class Design Lesson - 4.
Exceptions Used to signal errors or unexpected situations to calling code Should not be used for problems that can be dealt with reasonably within local.
06 - Exceptions. 2 ©S. Uchitel, 2004 A familiar sight? Bluescreen.scr.
Java Methods By J. W. Rider. Java Methods Modularity Declaring methods –Header, signature, prototype Static Void Local variables –this Return Reentrancy.
MT311 Java Application Development and Programming Languages Li Tak Sing( 李德成 )
Abstract Data Types (ADTs) and data structures: terminology and definitions A type is a collection of values. For example, the boolean type consists of.
220 FINAL TEST REVIEW SESSION Omar Abdelwahab. INHERITANCE AND POLYMORPHISM Suppose you have a class FunClass with public methods show, tell, and smile.
CSM-Java Programming-I Spring,2005 Objects and Classes Overview Lesson - 1.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
Handling Exceptions in java. Exception handling blocks try { body-code } catch (exception-classname variable-name) { handler-code }
Spring 2008 Mark Fontenot CSE 1341 Principles of Computer Science I Note Set 10.
Practice Session 9 Exchanger CyclicBarrier Exceptions.
1 Features of Java (2) CS 3331 Sections 4.5 and 4.6.
Exceptions and Assertions Chapter 15 – CSCI 1302.
Exceptions in Java. What is an exception? An exception is an error condition that changes the normal flow of control in a program Exceptions in Java separates.
Exception-Handling Fundamentals  A Java exception is an object that describes an exceptional (that is, error) condition that has occurred in a piece of.
MIT AITI 2004 – Lecture 14 Exceptions Handling Errors with Exceptions.
Exceptions Lecture 11 COMP 401, Fall /25/2014.
LECTURE 8: EXCEPTIONS CSC 212 – Data Structures. Error Handling Goals  What should we do when an error occurs?  Should alert system to the error  May.
Topics Instance variables, set and get methods Encapsulation
Lecture10 Exception Handling Jaeki Song. Introduction Categories of errors –Compilation error The rules of language have not been followed –Runtime error.
OOP Basics Classes & Methods (c) IDMS/SQL News
Exceptions and Error Handling. Exceptions Errors that occur during program execution We should try to ‘gracefully’ deal with the error Not like this.
Section 3.3 Exceptional Situations. 3.3 Exceptional Situations Exceptional situation Associated with an unusual, sometimes unpredictable event, detectable.
Garbage Collection It Is A Way To Destroy The Unused Objects. To do so, we were using free() function in C language and delete() in C++. But, in java it.
1 Stacks Abstract Data Types (ADTs) Stacks Application to the analysis of a time series Java implementation of a stack Interfaces and exceptions.
Basic Class Structure. Class vs. Object class - a template for building an object –defines the instance data that the object will hold –defines instance.
Object Throwable ErrorException RuntimeException.
Information and Computer Sciences University of Hawaii, Manoa
Stacks II David Lillis School of Computer Science and Informatics
Exceptions In this lecture:
Examples of Classes & Objects
Exceptions: When things go wrong
Chapter 10 – Exception Handling
Queues Rem Collier Room A1.02
OBJECT ORIENTED PROGRAMMING II LECTURE 10 GEORGE KOUTSOGIANNAKIS
MIT AITI 2003 Lecture14 Exceptions
Introduction to Exceptions in Java
Introduction Exception handling Exception Handles errors
Introduction to Exceptions in Java
Creating and Modifying Text part 2
Handling Exceptions.
Advanced Programming Behnam Hatami Fall 2017.
ATS Application Programming: Java Programming
Exceptions Handling the unexpected
Java Programming Language
Classes & Objects: Examples
Group Status Project Status.
Lecture 9: Exceptions in Java CS201j: Engineering Software
CMSC 202 Exceptions 2nd Lecture.
CMSC 202 Exceptions 2nd Lecture.
Web Design & Development Lecture 7
Stacks Abstract Data Types (ADTs) Stacks
Lecture 11 Objectives Learn what an exception is.
Java Exceptions Dan Fleck CS211.
CMSC 202 Exceptions 2nd Lecture.
Errors and Exceptions Error Errors are the wrongs that can make a program to go wrong. An error may produce an incorrect output or may terminate the execution.
Introduction to Object-Oriented Concepts in Java
Java Basics Exception Handling.
CMSC 202 Exceptions 2nd Lecture.
Java Programming: From Problem Analysis to Program Design, 4e
A type is a collection of values
Presentation transcript:

Exceptions, Interfaces & Generics Rem Collier Room A1.02 School of Computer Science and Informatics University College Dublin, Ireland

Exceptions

Exceptions An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions. Exceptions: Stop execution of the current method. Force the Java interpreter to enter exception handling mode Are represented in Java as objects Exception are generated by creating and throwing an Exception object. Exception Handling Mode = the search for an exception handler It checks the current method for an appropriate handler. No handler => throw exception to the invoking method and return to 1. If no method handles the exception, then the program stops. Exceptions are handled by the Java try … catch statement.

Exception Example public class Test { public static void main(String[] args) { try { test(); } catch (Exception e) { e.printStackTrace(); } System.out.println(“Yipee!”); public static void test() throws Exception { throw new Exception("An exception"); Example Output: java.lang.Exception: An exception at Test.test(Test.java:22) at Test.main(Test.java:15) Yipee!

Unchecked Exceptions Checked Exceptions: Unchecked Exceptions: All methods must explicitly declare that they throw the exception Corresponding method invocations must: Either be nested within a try…catch statement Or declare that they will throw the exception Are used for handling recoverable, anticipated errors E.g. trying to open a file that does not exists Unchecked Exceptions: Methods do not need to explicitly declare that they throw the exception. Corresponding invocations do not need to declare or handle the exception Are used for non-recoverable, unexpected errors E.g. trying to access an index that is outside the bounds of the array

Exception Example public class Test { public static void main(String[] args) { test(); System.out.println(“Yipee!”); } public static void test() { throw new RuntimeException("An exception"); Example Output: Exception in thread "main" java.lang.RuntimeException: An exception at Test.test(Test.java:19) at Test.main(Test.java:14)

Meaningful Exceptions Exception and RuntimeException are not very instructive in helping you understand what happened. They rely on the developer providing a meaningful message (often this does not happen) Some methods may throw multiple different types of exception depending on what goes wrong A better approach is to create your own exception types: This is done by extending the Exception or RuntimeException class and creating a new exception class that has a meaningful name. Examples: Java uses the FileNotFoundException class to indicate that you tried to open a file that does not exist. An unchecked ArrayIndexOutOfBoundsException is thrown whenever you try to access an array position that is outside its declared range. Some help on exceptions: http://java.sun.com/docs/books/tutorial/essential/exceptions/index.html

Exceptions & ADTs public class StackEmptyException extends RuntimeException {} public class StringStack { … public String pop() { if (top == 0) throw new StackEmptyException(); } public static void main(String[] args) { StringStack stack = new StringStack(); String s = stack.pop();

Exceptions & ADTs Why is StackEmptyException not checked? public static void main(String[] args) { StringStack stack = new StringStack(); boolean finished = false; while (!finished) { try { stack.pop(); } catch (StackEmptyException e) { finished = true; } pop() should never be called on an empty stack – making the exeception checked opens up code like this…

Interfaces

OOP Revisited Core Concept: Class Fields (static / non-static) Methods (static / non-static) Constructors Inner Classes Classes (primarily) define object types. Objects exist at run-time only! Classes encapsulate real world concepts: They model the informational and functional requirements. Abstract Data Types are implemented using classes. For “full encapsulation” the implementation must also be hidden…

Java Accessibility Modifiers Defines how visible a class, field, method, … is Prefix the field, method, … with the modifier Visibility is a lot like scope: Specifies where and when in a program a given class, field, method, … can be used Java has four levels of visibility: public - accessible anywhere. private - accessible only in the class in which they are declared. protected - accessible in the class in which they are declared, and any subclass of that class. no prefix - accessible from anywhere within the same package.

Visibility Example 1 public class Rectangle { int breadth; int length; public Rectangle(int _breadth, int _length) { breadth = _breadth; length = _length; } public int area() { return breadth * length; public class RectangleTest { public static void main(String[] args) { Rectangle rectangle = new Rectangle(10, 5); System.out.println("Rectangle with a length of " + rectangle.length +" and a breadth of " + rectangle.breadth + " has area: " + rectangle.area());

Visibility Example 2 public class Rectangle { private int breadth; private int length; public Rectangle(int _breadth, int _length) { breadth = _breadth; length = _length; } public int area() { return breadth * length; public class RectangleTest { public static void main(String[] args) { Rectangle rectangle = new Rectangle(10, 5); System.out.println("Rectangle with a length of " + rectangle.length +" and a breadth of " + rectangle.breadth + " has area: " + rectangle.area());

Abuse Example public class BankAccount { public double balance; public boolean withdraw(double amount) { if (balance > amount) { balance -= amount; return true; } return false; public Abuser { public static void main(String[] args) { BankAccount account = new BankAccount(); account = 1000.0; boolean success; do { success = account.withdraw(330.0); } while (success); account.balance -= 500.0;

Public Interfaces Accessibility modifiers => control use of methods / fields / classes. Helps “Stupidity Management”: e.g. stopping a Stack Node class being used in a Deque class Public Interface: the parts of your code that are accessible from outside the class i.e. everything that is declared public Defines what you can do, not how it does it Programming to Interfaces (Best Practices in SE): Identify the public interface early, define it, and publish it (to your colleagues) Now, think about implementation Colleagues write code that conforms to the interface and not your implementation.

Interfaces in Java Interface types constrain what you can do: In Java, Interfaces are a concrete concept: They are not classes Declared via the interface keyword Consists of a set of public method signatures No method implementations Classes can implement interfaces: Declared via the implements keyword All interface methods must be implemented Interfaces are types: Interface type variables, fields, parameters can reference any class that implements the interface Interface types constrain what you can do: Only methods declared in the interface can be invoked

Interface Example public interface MyInterface { public void hello(); } public class MyClass implements MyInterface { public void hello() { System.out.println(“Hello World!”); public void goodbye() { System.out.println(“Goodbye World!”); public class Test { public static void main(String[] args) { MyInterface iface = new MyClass(); iface.hello(); iface.goodbye();

Interfaces & ADTs public interface Stack { public void push (Object element); public Object pop(); public int size(); public boolean isEmpty(); public Object top(); } public class ArrayStack implements Stack { … } public class LinkedStack implements Stack { … } public static void main(String[] args) { Stack stack = new ArrayStack(); stack.push(“England”); stack.push(“France”); … String s = (String) stack.pop();