Computer Science [3] Java Programming II - Laboratory Course Lab 3-1: Creating and Using Interfaces Exception Faculty of Engineering & IT Software Engineering.

Slides:



Advertisements
Similar presentations
Topics Introduction Types of Errors Exceptions Exception Handling
Advertisements

Object Oriented Programming
Exception Handling. Introduction Errors can be dealt with at place error occurs –Easy to see if proper error checking implemented –Harder to read application.
Exceptions & exception handling Use sparingly. Things you can do with exceptions: 1. Define a new exception class. 2. Create an exception instance. 3.
Exceptions Ensuring program reliability. Program correctness The term program correctness refers to a program’s working as advertised; that is, it produces.
Exceptions Don’t Frustrate Your User – Handle Errors KR – CS 1401 Spring 2005 Picture – sysprog.net.
Exception Handling Chapter 15 2 What You Will Learn Use try, throw, catch to watch for indicate exceptions handle How to process exceptions and failures.
Outline DivideByZeroTes t.java 1 // Fig. 15.1: DivideByZeroTest.java 2 // An exception-handling example that checks for divide-by-zero. 3 import java.awt.*;
 2003 Prentice Hall, Inc. All rights reserved. Chapter 15 – Exception Handling Outline 15.1 Introduction 15.2 Exception-Handling Overview 15.3 Exception-Handling.
Java I/O Java I/O is based on input streams and output streams. All input and output are defined in the Java IO package. 1.
Exception Handling Yaodong Bi Exception Handling Java exception handling Try blocks Throwing and re-throwing an exception Catching an.
بسم الله الرحمن الرحيم CPCS203: Programming II. Objectives After you have read and studied this chapter, you should be able to –Improve the reliability.
Exception Handling1. 2 Exceptions  Definition  Exception types  Exception Hierarchy  Catching exceptions  Throwing exceptions  Defining exceptions.
 2002 Prentice Hall, Inc. All rights reserved. Chapter 14 – Exception Handling Outline 14.1 Introduction 14.2 When Exception Handling Should Be Used 14.3.
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 10 GEORGE KOUTSOGIANNAKIS Copyright: 2014 Illinois Institute of Technology/ George Koutsogiannakis 1.
Exception Handling Chapter 12.  Errors- the various bugs, blunders, typos and other problems that stop a program from running successfully  Natural.
Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.
Exceptions Briana B. Morrison CSE 1302C Spring 2010.
Understand Error Handling Software Development Fundamentals LESSON 1.4.
Exception Handling. Introduction An exception is an abnormal condition that arises in a code sequence at run time. In computer languages that do not support.
1 Lecture 11 Interfaces and Exception Handling from Chapters 9 and 10.
1 More on Threads b b A section of code executed independently of other threads written within a single program. b b Java threads can access global data;
Exception handling Dealing with life’s little surprises.
1 Java - Threads A thread is an individual flow of control within a larger program. A program which is running more than one thread is said to be multithreaded.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 14 - Exception Handling Outline 14.1Introduction 14.2When Exception Handling Should Be Used 14.3Other.
Chapter 11: Handling Exceptions and Events J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Fourth.
Exception Handling Recitation – 10/(23,24)/2008 CS 180 Department of Computer Science, Purdue University.
Exception Handling (Chapter 8) CS 180 Recitation - February 29, 2008 Department of Computer Science Purdue University.
Chapter 13 Exception Handling F Claiming Exceptions F Throwing Exceptions F Catching Exceptions F Rethrowing Exceptions  The finally Clause F Cautions.
Exception Handling in Java Exception Handling Introduction: After completing this chapter, you will be able to comprehend the nature and kinds.
Java Programming Exception Handling. The exception handling is one of the powerful mechanism provided in java. It provides the mechanism to handle the.
1 Review of Java Higher Level Language Concepts –Names and Reserved Words –Expressions and Precedence of Operators –Flow of Control – Selection –Flow of.
Introduction to Programming David Goldschmidt, Ph.D. Computer Science The College of Saint Rose Java Fundamentals (Comments, Variables, etc.)
Computer Science [3] Java Programming II - Laboratory Course Lab 1 + 2: Review inheritance & abstract Review inheritance & abstractPolymorphism Faculty.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Spring 2008 Mark Fontenot CSE 1341 Principles of Computer Science I Note Set 10.
Exception Handling Unit-6. Introduction An exception is a problem that arises during the execution of a program. An exception can occur for many different.
Exceptions in Java. Exceptions An exception is an object describing an unusual or erroneous situation Exceptions are thrown by a program, and may be caught.
Sadegh Aliakbary Sharif University of Technology Fall 2010.
Data Structures Using Java1 Chapter 2 Inheritance and Exception Handling.
Chapter 12 Handling Exceptions and Events. Chapter Objectives Learn what an exception is Become aware of the hierarchy of exception classes Learn about.
Sheet 3 HANDLING EXCEPTIONS Advanced Programming using Java By Nora Alaqeel.
Pengantar OOP Class-Java. 2 Software Development Tools Using Sun Java SDK alone Source File(s) (.java) Programmer Compiler (javac) Class File(s) (.class)
Java Programming: From Problem Analysis to Program Design, 4e Chapter 11 Handling Exceptions and Events.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 14 - Exception Handling Outline 14.1Introduction 14.2When Exception Handling Should Be Used 14.3Other.
Exception Handling in Java Topics: Introduction Errors and Error handling Exceptions Types of Exceptions Coding Exceptions Summary.
Exception-Handling Fundamentals  A Java exception is an object that describes an exceptional (that is, error) condition that has occurred in a piece of.
EXCEPTIONS There's an exception to every rule.. 2 Introduction: Methods  The signature of a method includes  access control modifier  return type 
© 2006 Pearson Addison-Wesley. All rights reserved 1-1 Chapter 1 Review of Java Fundamentals.
Exception Handling How to handle the runtime errors.
COP 3330 Notes 3/7. Today’s Topics Exceptions Abstract Classes.
1 Flow of Control Chapter 5. 2 Objectives You will be able to: Use the Java "if" statement to control flow of control within your program.  Use the Java.
Exceptions and Error Handling. Exceptions Errors that occur during program execution We should try to ‘gracefully’ deal with the error Not like this.
DCS 2133 Object Oriented Programming ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Exception Handling.
Agenda Introduction Errors and Exception Exception Hierarchy Classification of Exceptions Built in Exceptions Exception Handling in Java User defined.
Exception Handling. You learned that there are three categories of errors: syntax errors, runtime errors, and logic errors. Syntax errors arise because.
Chapter 14 – Exception Handling
Chapter 10 – Exception Handling
Interface.
Exceptions & exception handling
Exceptions & exception handling
Chapter 12 Exception Handling and Text IO
Fundamental Error Handling
Exception Handling in Java
Lecture 11 Objectives Learn what an exception is.
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.
Tutorial Exceptions Handling.
Java Programming: From Problem Analysis to Program Design, 4e
Chapter 15 – Exception Handling
INTERFACES Explained By: Sarbjit Kaur. Lecturer, Department of Computer Application, PGG.C.G., Sector: 42, Chandigarh.
Presentation transcript:

Computer Science [3] Java Programming II - Laboratory Course Lab 3-1: Creating and Using Interfaces Exception Faculty of Engineering & IT Software Engineering Department Eng.Omar Al-Nahal Eng.Omar Al-Nahal

What is interface? Because an interface is simply a list of unimplemented, and therefore abstract, methods, you might wonder how an interface differs from an abstract class. The differences are significant. b b An interface cannot implement any methods, whereas an abstract class can. b b A class can implement many interfaces but can have only one superclass. b b An interface is not part of the class hierarchy. Unrelated classes can implement the same interface Definition: An interface is a collection of method definitions (without implementations) and constant values.

Defining an Interface b To create an interface, you must write both the interface declaration and the interface body. - interfaceDeclaration { interfaceBody } - interfaceDeclaration { interfaceBody } The interfaceDeclaration declares various attributes about the interface such as its name and whether it extends another interface. The interfaceDeclaration declares various attributes about the interface such as its name and whether it extends another interface. The interfaceBody contains the constant and method declarations within the interface. The interfaceBody contains the constant and method declarations within the interface. b The Interface Declaration: At minimum, the interface declaration contains the Java keyword interface and the name of the interface that you are creating: At minimum, the interface declaration contains the Java keyword interface and the name of the interface that you are creating: interface Countable { interface Countable {... }... } b interface declaration looks like this: [public] interface InterfaceName [extends listOfSuperInterfaces] {... } [public] interface InterfaceName [extends listOfSuperInterfaces] {... }

Using an Interface - An interface gets used when a class claims to implement that interface. A class declares all of the interfaces that it implements in its class declaration. - An interface gets used when a class claims to implement that interface. A class declares all of the interfaces that it implements in its class declaration. - To declare that your class implements one or more interfaces, use the keyword implements followed by a comma-delimited list of the interfaces implemented by your class. - To declare that your class implements one or more interfaces, use the keyword implements followed by a comma-delimited list of the interfaces implemented by your class. - The FIFOQueue class would declare that it implements the Countable interface like this : - The FIFOQueue class would declare that it implements the Countable interface like this : class FIFOQueue implements Countable {... }

Interfaces Do Not Provide Multiple Inheritance Interfaces are different from multiple inheritance in: you cannot inherit variables from an interfaceyou cannot inherit variables from an interface you cannot inherit method implementations from an interface.you cannot inherit method implementations from an interface. the interface hierarchy is independent of a the class hierarchy--classes that implement the same interface may or may not be related through the class hierarchy. This is not true for multiple inheritance.the interface hierarchy is independent of a the class hierarchy--classes that implement the same interface may or may not be related through the class hierarchy. This is not true for multiple inheritance.

Interface Example 1 b b interface Shape { b b float area(); bb}bb} b b class Circle implements Shape{ b b private float r; b b public Circle(float r){ b b this.r = r; bb}bb} b b public float area(){ b b return (float) (Math.PI * r * r); bb}bb} bb}bb} b b class Rectangle implements Shape { b b private float l, w; b b public Rectangle(float l, float w){ b b this.l = l; b b this.w = w; bb}bb}b

Interface Examples b b public float area(){ b b return l*w; bb}bb} bb}bb} b b class Example1 { b b public static void main(String args[]){ b b Shape s[] = new Shape[3]; b b s[0] = new Circle(7.5f); b b s[1] = new Rectangle(10,3.5f); b b s[2] = new Circle(9);b b b for (int i = 0;i < 3;i++) b b System.out.println(s[i].area()); bb}bb} bb}bb}

Interface Example 2 b interface MySubject { b int arabic = 1; b int english = 2; b int physics = 3; b b}b}b}b} b class One implements MySubject{ b public static void main(String args[]){ b System.out.println(arabic); b}b}b}b} b}b}b}b} b class Two { b public static void main(String args[]){ b System.out.println(MySubject.english); b}b}b}b} b}b}b}b}

Exception Handling Overview b Keywords TryTry –Include codes in which exceptions might occur CatchCatch –Represent types of exceptions the catch can handle FinallyFinally –(Optional) codes present here will always execute b Exception handling Process synchronous errorsProcess synchronous errors Follows the termination model of exception handlingFollows the termination model of exception handling

try-catch Syntax try{ } catch ( ) { } catch ( ) { }…

Example: DivideByZeroException b Error catching Method Convert.ToInt32 will automatically detect for invalid representation of an integerMethod Convert.ToInt32 will automatically detect for invalid representation of an integer –Method generates a FormatException CLR automatic detection for division by zeroCLR automatic detection for division by zero –Occurrence will cause a DivideByZeroException // Fig. 13.1: DivideByZeroNoExceptionHandling.java import java.util.Scanner; public class ex01 { // demonstrates throwing an exception when a divide-by-zero occurs public static int quotient( int numerator, int denominator ) { return numerator / denominator; // possible division by zero } // end method quotient public static void main( String args[] ) {

Example: DivideByZeroException Scanner scanner = new Scanner( System.in ); // scanner for input System.out.print( "Please enter an integer numerator: " ); int numerator = scanner.nextInt(); System.out.print( "Please enter an integer denominator: " ); int denominator = scanner.nextInt(); int result = quotient( numerator, denominator ); System.out.printf( "\nResult: %d / %d = %d\n", numerator, denominator, result ); } // end main } // end class DivideByZeroNoExceptionHandling Please enter an integer numerator: 100 Please enter an integer denominator: 0 Exception in thread "main" java.lang.ArithmeticException: / by zero at DivideByZeroNoExceptionHandling.quotient(DivideByZeroNoException- Handling.java:10) at DivideByZeroNoExceptionHandling.main(DivideByZeroNoExceptionHan- dling. java:22) Output: Please enter an integer numerator: 100 Please enter an integer denominator: 7 Result: 100 / 7 = 14

Throwing Exceptions

Finally clause b What if there is some code we want to execute regardless of exception or not? finally block is usedfinally block is used try{ distance = Double.parseDouble(str); if (distance < 0){ throw new Exception("Negative distance is not valid"); } return distance; } catch (NumberFormatException e){ System.out.println("'" + str + "'not valid input, Please use digits only"); } catch (Exception e){ System.out.println(e.getMessage()); } finally { System.out.println(“Done”); }

try-catch Control Flow code before try try block code after try no exceptions occur code before try try block catch block exception occurs code after try

try-catch Control Flow try block exception occurs code after try code before tryfinally block (if it exists)catch block

Example class Example1{ public static void f(int x) throws Exception{ if (x<0) throw new Exception("NegativeNotAllowedException"); //else System.out.println(" X is "+x); } public static void main(String args[]){ try { f(4); } catch(Exception e){ System.out.println(e); } finally{} } } class One { public static void main(String args[]){ int x=4, m, y=0; try { m = x/y; } catch(ArithmeticException e){ System.out.println(e); } int a[] = {4,5,6,7}; try { a[8] = 10; } catch(ArrayIndexOutOfBoundsException e){ System.out.println(e); }} }