Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Object-Oriented Programming (Java) Topics Covered Today • Unit 1.1 Java Applications – 1.1.5 Exception Objects – 1.1.6 Code Convention – 1.1.7 Javadoc 2 Program Errors • Syntax (compiler) 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 3 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 4 Method readInteger() • Pseudo-code for a method that reads an integer from the standard input: int readInteger () { } Read a string from the standard input Convert the string to an integer value Return the integer value • 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". 5 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; }}}} 6 Exception Handling • Exception handling is a mechanism that allows failures to be handled outside the normal flow of the code. – 将程序运行中的所有错误都看成一种异常,通过对语 句块的检测,一个程序中的所有异常被集中起来放到 程序中的某一段中进行处理 int readInteger () { while (true) { try { normal flow of the code read a string from the standard input; convert the string to an integer value; return the integer value; each failure is handled in } catch (read from the standard input failed) { a catch handle standard input error; block } catch (the string does not contain an integer) { handle invalid number format error; 7 } }} Run-time Exception public class DivideByZero { public static void main(String[] args) { System.out.println(5/0); System.out.println("this will not be printed."); System.out.println("Division by zero."); } } Exception in thread "main" java.lang.ArithmeticException: / by zero at DivideByZero.main(DivideByZero.java:9) 8 try-catch public class DivideByZero1 { 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 9 Exception Object • In Java, an exception is an object that describes an abnormal situation. • 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 10 Method of Exception • String getMessage(). – 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. 11 Exception Class Hierarchy 12 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. 13 Exception Class Hierarchy • Class Exception is used for abnormal conditions that an application can be expected to handled. 14 Checked & Unchecked Exception • Two types of exceptions checked & unchecked by compiler 15 Unchecked Exceptions • Error & RunTimeException • Serious errors not handled by typical program • Example – NullPointerException – IndexOutOfBoundsException • Catching unchecked exceptions is optional • Handled by Java Virtual Machine if not caught 16 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. 17 CheckedExceptionDemo.java import java.io.*; public class CheckedExceptionDemo { public static void main(String[] args) { FileInputStream stream = new FileInputStream(args[0]); // Process file … // ... stream.close(); } } 18 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 错误 19 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."); } } } 20 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(); } } 21 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. 22 OutOfRangeException.java public class OutOfRangeException extends Exception { public OutOfRangeException() { } public OutOfRangeException(String message) { super(message); } 23 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"); 24 Throw Exception A( ) throws OutOfRangeException { if (error) throw new OutOfRangeException(); } B( ) { try { A( ); } catch (OutOfRangeException e) { ...action... } } 25 Exception Handling 26 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); } } 27 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"); } } 28 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(); public static void methodB() throws Exception { System.exit(1); 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"); } } 29 Execution Result of ExceptionDemo.java Exception Name Call Stack 30 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(); } 31 Generating & Handling Exceptions • Java primitives – – – – try throw catch finally • 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 32 Java Syntax try { throw new eType1(); } catch (eType1 e) { ...action... } catch (eType2 e) { ...action... } finally { ...action... } // try block encloses throws // throw jumps to catch // catch block 1 // run if type match // catch block 2 // run if type match // final block // optional, always be executed 33 Topics Covered Today • Unit 1.1 Java Applications – 1.1.5 Exception Objects – 1.1.6 Code Convention – 1.1.7 Javadoc 34 Why need Code Convention? • 专业编码工作的产品将会是你的源代码。对于任何商 业的产品,应该确定你的代码有最高的质量。 • 要是代码要保存很长一段时间,你必须使得你的代码 可读以及便于其他人所理解。难于理解的代码可能要 舍弃和重写。 • 作为开发团队的一部分,你应该致力于你的代码和你 的队友的保持一致。 • 编码的风格一般反映你是什么样的程序员。清晰的和 整齐的代码常常反映出一个拥有清晰头脑,组织能力 很强的程序员。 35 Java Code Conventions • http://java.sun.com/docs/codeconv/html/CodeConvTOC.d oc.html • Java Code Conventions Quick Reference 36 Topics Covered Today • Unit 1.1 Java Applications – 1.1.5 Exception Objects – 1.1.6 Code Convention – 1.1.7 Javadoc 37 JAVA Comments • // single line comment • /* */ multi-line comment • Javadoc 38 JavaDoc and Javadoc Program • Javadoc 解析 Java 源文件中的声明和文档注释,并产 生相应的 HTML 页(缺省),描述公有类、保护类、 内部类、接口、构造函数、方法和域。 • 维护软件比开发软件花费的更多,如果软件很好的归 档,维护工作将很容易。很多程序员在软件开发完后 才归档,这是错误的。编码完成时归档也应该结束。 • 使用Javadoc可增强归档。 • 整个Java API的文档使用Javadoc形式。 39 Javadoc Syntax • Javadoc comments open with a "slash-asterisk-asterisk" sequence ( /** ) and close with an "asterisk-slash" sequence ( */ ) on the same line or on separate lines. • Each internal line begins with a single asterisk ( * ) . • For example: /** * body text /** body text */ * body text * body text */ 40 Some Useful Tags • @author – programmer's name; used for classes • @version – version of the program; used for classes • @param – description of a formal parameter; used for methods and constructors • @return – description of a return value; used for methods • @exception (or @throws) – description of an exception; used for methods and constructors • @see – reference to a related entity; used for classes, constructors, methods, and data fields • http://java.sun.com/j2se/javadoc/index.html 41 Including HTML Tags <P>…</P> Paragraph <BR> Line break <UL>…</UL> <LI>…</LI> List <I>…</I> italics <B>…</B> boldface <CODE>…</CODE> fixed width (Should not use <H1>, <H2>, etc.) 42 Javadoc Command • A program that automatically extracts documentation from your Java sources. • For each source file MyClass.java, it will create a MyClass.html, plus a couple of additional pages. • Example: – Unit1.1.7 TwoInts.java 43 Running Javadoc Figure 1 Javadoc command 44 Options to the javadoc program -public Only extract comments for public items -private -author -d dir -link url Extract all comments Include author information Specify output directory Include links to Java API javadoc -private -author -d docs TwoInts.java 45 Use JavaDoc with Eclipse 46