Presentation is loading. Please wait.

Presentation is loading. Please wait.

Introduction to OO Program Design

Similar presentations


Presentation on theme: "Introduction to OO Program Design"— Presentation transcript:

1 Introduction to OO Program Design
Software College of SCU Instructor: Shu, Li week03

2 Unit 1.1 Java Applications
Topics Covered Today Unit 1.1 Java Applications 1.1.5 Exception Objects 1.1.6 Code Convention

3 Program Errors Syntax (compiler) errors Run-time errors Logic errors
Errors in code construction (grammar, types) Detected during compilation Run-time errors Operations illegal / impossible to execute Detected during program execution Treated as exceptions in Java Logic errors Operations leading to incorrect program state May (or may not) lead to run-time errors Detect by debugging code

4 Exceptions An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions. Examples Division by zero Access past end of array Out of memory Number input in wrong format (float vs. integer) Unable to write output to file Missing input file

5 Method readInteger() Pseudo-code for a method that reads an integer from the standard input: This pseudo-code ignores the failures that may occur: The string cannot be read from the standard input. For example, the standard input may be a damaged file. The string does not contain an integer. For example, the user may type "2r" instead of "25". int readInteger () { Read a string from the standard input Convert the string to an integer value Return the integer value }

6 The Traditional Approach
Include conditional statements to detect and handle program failures. The code is difficult to read and maintain. int readInteger () { while (true) { read a string from the standard input; if (read from the standard input fails) { handle standard input error; } else { convert the string to an integer value; if (the string does not contain an integer) { handle invalid number format error; } else { return the integer value;

7 each failure is handled in a catch block
Exception Handling Exception handling is a mechanism that allows failures to be handled outside the normal flow of the code. 将程序运行中的所有错误都看成一种异常,通过对语句块的检测,一个程序中的所有异常被集中起来放到程序中的某一段中进行处理. normal flow of the code int readInteger () { while (true) { try { read a string from the standard input; convert the string to an integer value; return the integer value; } catch (read from the standard input failed) { handle standard input error; } catch (the string does not contain an integer) { handle invalid number format error; } } } each failure is handled in a catch block

8 An Example of Exception Handling
// DivideByZero.java public class DivideByZero { public static void main(String[] args) System.out.println(5/0); System.out.println("this will nor be printed."); System.out.println("Division by zero."); } // main } Exception in thread "main" java.lang.ArithmeticException: / by zero at DivideByZero.main(DivideByZero.java:9)

9 Using try-catch Statement
public class DivideByZero { public static void main(String[] args) try { System.out.println(5/0); } catch (Exception e) { System.out.printf("Caught runtime exception = %s", e); } Caught runtime exception = java.lang.ArithmeticException: / by zero

10 Exception Object. In Java, an exception is an object that describes an abnormal situation. public class DivideByZero { public static void main(String[] args) try { System.out.println(5/0); } catch (Exception e) { System.out.printf("Caught runtime exception = %s", e); }

11 An exception object contains the following information:
The kind of exception A call stack which indicates where the exception occurred A string with additional information about the exception

12 Method of Exception. String getMessage(). String toString().
Obtains the argument that was passed to the constructor of the exception object. String toString(). The name of the exception (its type), followed by a colon ( : ), followed by the String returned by method getMessage. void printStackTrace(). This method displays, in the standard error stream, the String returned by method toString, followed by information that shows where the exception was thrown. The information includes a list of all the methods that were called before the exception occurred.

13 Method of Exception.. public class DivideByZero {
public static void main(String[] args) try { System.out.println(5/0); } catch (Exception e) { System.out.printf("%s\n", e.getMessage()); System.out.printf("%s\n", e.toString()); e.printStackTrace(); } F:\my teaching\2014S\week03>java DivideByZero / by zero java.lang.ArithmeticException: / by zero at DivideByZero.main(DivideByZero.java:6)

14 What kinds of exceptions occurred in your labs?
Type of Exceptions What kinds of exceptions occurred in your labs? java.lang.ArithmeticException: / by zero java.lang.NumberFormatException: For input string: "4.0" java.lang.ArrayIndexOutOfBoundsException: 0 java.lang.ClassNotFoundException: Helloworld

15 Exception Class Hierarchy

16 Exception Class Hierarchy
Only objects that are instances of this class (or one of its subclasses) are thrown by the Java Virtual Machine or can be thrown by the Java throw statement. Similarly, only this class or one of its subclasses can be the argument type in a catch clause.

17 Exception Class Hierarchy
Class Error is used for serious problems from which an application is unlikely to recover. An example is the "out of memory" error.

18 Exception Class Hierarchy
Class Exception is used for abnormal conditions that an application can be expected to handled.

19 Checked & Unchecked Exception
Two types of exceptions  checked & unchecked by compiler

20 Error & RunTimeException Example
Unchecked Exceptions Error & RunTimeException Example NullPointerException IndexOutOfBoundsException Catching unchecked exceptions is optional Handled by Java Virtual Machine if not caught

21 Class Exception (except RunTimeException)
Checked Exceptions Class Exception (except RunTimeException) Errors typical program should handle Example IOException, FileNotFoundException Compiler requires “catch or declare” Catch and handle exception in method, OR Declare method can throw exception, force calling function to catch or declare exception in turn.

22 CheckedExceptionDemo.java import java.io.*;
public class CheckedExceptionDemo { public static void main(String[ ] args) { FileInputStream stream = new FileInputStream (args[0]); // Process file … // ... stream.close(); }

23 Code Compile Errors F:\My Teaching\ssd3f07\>javac CheckExceptionDemo.java CheckExceptionDemo.java:4: 未报告的异常 java.io.FileNotFoundException;必须对其进行捕捉或声明以便抛出 FileInputStream stream = new FileInputStream(args[0]); ^ CheckExceptionDemo.java:7: 未报告的异常 java.io.IOException;必须对其进行捕捉或声明以便抛出 stream.close(); 2 错误

24 Catching Multiple Exceptions
import java.io.*; public class CheckExceptionDemo { public static void main(String[] args) { try { FileInputStream stream = new FileInputStream(args[0]); stream.close(); } catch (ArrayIndexOutOfBoundsException aiobe) { System.err.println("The program needs a command argument."); } catch (FileNotFoundException exception) { System.err.println("Cannot find file '" + args[0] + "'"); } catch (SecurityException exception) { System.err.println("No permissions for '" + args[0] + "'"); } catch (IOException ioe) { System.err.println("Close file error."); } } }

25 Throws Exceptions Checked exceptions could be declared in the method header using throws. import java.io.*; public class CheckExceptionDemo { public static void main(String[] args) throws IOException // declares exception { FileInputStream stream = new FileInputStream(args[0]); stream.close(); }

26 Raised implicitly by system Raised explicitly by programmer
Exception Occurrence Raised implicitly by system System-Defined Exceptions Raised explicitly by programmer User-Defined Exceptions

27 System-Defined Exception
IndexOutOfBoundsException : When beyond the bound of index in the object which use index, such as array, string, and vector ArrayStoreException : When assign object of incorrect type to element of array NegativeArraySizeException : When using a negative size of array NullPointerException : When refer to object as a null pointer SecurityException : When violate security. Caused by security manager IllegalMonitorStateException : When the thread which is not owner of monitor involves wait or notify method

28 User-Defined Exceptions
A new checked exception class can be defined by extending the class Exception. A new unchecked exception class can be defined by extending the class RuntimeException.

29 OutOfRangeException.java public class OutOfRangeException extends Exception { public OutOfRangeException() { } public OutOfRangeException(String message) { super(message); }

30 The throw Statement. User-defined methods can also throw exceptions. To throw an exception, use the keyword throw, following by an exception object. For example: throw new OutOfRangeException(); throw new OutOfRangeException("Not a valid number");

31 The throw Statement.. public void printAge (int age) throws OutOfRangeException { if (age<0 || age>200) {   OutOfRangeException e = new OutOfRangeException(“age exception”);   throw e;  //抛出异常 } System.out.println(age); } int age; age = -100; if (age<0) {   Exception e = new Exception("Age Exception");  //创建异常对象   throw e;  //抛出异常 } System.out.println(age);

32 Throw Exception A( ) throws OutOfRangeException {
if (error) throw new OutOfRangeException(); } B( ) { try { A( ); catch (OutOfRangeException e) { ...action... }

33 Chained Exceptions An application often responds to an exception by throwing another exception. In this example, when an IOException is caught, a new SampleException exception is created with the original cause attached and the chain of exceptions is thrown up to the next higher level exception handler. try { } catch (IOException e) { throw new SampleException("Other IOException", e); } 链式异常, 异常链

34 Exception Handling

35 ExceptionDemo.java public class ExceptionDemo {
public static void main(String[] args)   { methodA(); System.out.println("MethodA passed");   } public static void   methodA()   { try { methodB(); System.out.println("MethodB passed"); } catch (Exception e) {    e.printStackTrace();      System.exit(1);     }

36 ExceptionDemo.java (Cont.)
public static void methodB() throws Exception { methodC();   System.out.println("MethodC passed"); } public static void methodC() throws Exception { methodD(); System.out.println("MethodD passed"); } public static void methodD() throws Exception { throw new Exception("This is an Exception Message"); } }

37 Execution Result of ExceptionDemo.java
public class ExceptionDemo { public static void main(String[] args){ methodA(); System.out.println("MethodA passed"); } public static void methodA() { try { methodB(); System.out.println("MethodB passed"); } catch (Exception e) { e.printStackTrace(); System.exit(1); public static void methodB() throws Exception { methodC(); System.out.println("MethodC passed"); } public static void methodC() throws Exception { methodD(); System.out.println("MethodD passed"); public static void methodD() throws Exception { throw new Exception("This is an Exception Message");

38 Execution Result of ExceptionDemo.java
Exception Name Call Stack

39 The finally Block FileInputStream stream1 = null;
FileOutputStream stream2 = null; try { stream1 = new FileInputStream(name1); stream2 = new FileOutputStream(name2); ... } catch (...) { } finally { if (stream2 != null) stream2.close(); if (stream1 != null) stream1.close(); }

40 Procedure for using exceptions
Summary. Java primitives try throw catch finally throws Procedure for using exceptions Enclose code generating exceptions in try block Use throw to actually generate exception Use catch to specify exception handlers Use finally to specify actions after exception 违例控制就是在程序中提供这样一种能力: 1)监视程序中的异常情况 2)当异常情况发生时,将控制权交给你自己编写的违例控制代码

41 Summary.. try { // try block encloses throws
throw new eType1(); // throw jumps to catch } catch (eType1 e) { // catch block 1 ...action // run if type match catch (eType2 e) { // catch block 2 finally { // final block ...action // optional, always be executed

42 Tutorial of Java Exception

43 Unit 1.1 Java Applications
Topics Covered Today Unit 1.1 Java Applications 1.1.5 Exception Objects 1.1.6 Code Convention

44 Why need Code Convention?
专业编码工作的产品将会是你的源代码。对于任何商业的产品,应该确定你的代码有最高的质量。 要是代码要保存很长一段时间,你必须使得你的代码可读以及便于其他人所理解。难于理解的代码可能要舍弃和重写。 作为开发团队的一部分,你应该致力于你的代码和你的队友的保持一致。 编码的风格一般反映你是什么样的程序员。清晰的和整齐的代码常常反映出一个拥有清晰头脑,组织能力很强的程序员。

45 Java Code Conventions Java Code Conventions Quick Reference


Download ppt "Introduction to OO Program Design"

Similar presentations


Ads by Google