470 likes | 506 Views
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. Program Errors. Syntax (compiler) errors Errors in code construction (grammar, types) Detected during compilation Run-time errors
E N D
Topics Covered Today • Unit 1.1 Java Applications • 1.1.5 Exception Objects • 1.1.6 Code Convention • 1.1.7 Javadoc
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
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
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 }
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; } } } }
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 { 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; } } } normal flow of the code each failure is handled in a catch block
Run-time Exception publicclass DivideByZero { publicstaticvoid 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)
try-catch publicclass DivideByZero1 { publicstaticvoid 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
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
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.
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.
Exception Class Hierarchy • Class Exception is used for abnormal conditions that an application can be expected to handled.
Checked & Unchecked Exception • Two types of exceptions checked & unchecked by compiler
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
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.
CheckedExceptionDemo.java import java.io.*; public class CheckedExceptionDemo { public static void main(String[] args){ FileInputStream stream =new FileInputStream(args[0]); // Process file … // ... stream.close(); } }
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 错误
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."); • } } }
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(); • } • }
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.
OutOfRangeException.java public class OutOfRangeException extends Exception { public OutOfRangeException() { } public OutOfRangeException(String message) { super(message); }
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");
Throw Exception A( ) throws OutOfRangeException { if (error) throw new OutOfRangeException(); } B( ) { try { A( ); } catch (OutOfRangeException e) { ...action... } }
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); } }
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"); } }
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"); } }
Execution Result of ExceptionDemo.java Exception Name Call Stack
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(); }
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
Java Syntax 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 ...action... // run if type match } finally { // final block ...action... // optional, always be executed }
Topics Covered Today • Unit 1.1 Java Applications • 1.1.5 Exception Objects • 1.1.6 Code Convention • 1.1.7 Javadoc
Why need Code Convention? • 专业编码工作的产品将会是你的源代码。对于任何商业的产品,应该确定你的代码有最高的质量。 • 要是代码要保存很长一段时间,你必须使得你的代码可读以及便于其他人所理解。难于理解的代码可能要舍弃和重写。 • 作为开发团队的一部分,你应该致力于你的代码和你的队友的保持一致。 • 编码的风格一般反映你是什么样的程序员。清晰的和整齐的代码常常反映出一个拥有清晰头脑,组织能力很强的程序员。
Java Code Conventions • http://java.sun.com/docs/codeconv/html/CodeConvTOC.doc.html • Java Code Conventions Quick Reference
Topics Covered Today • Unit 1.1 Java Applications • 1.1.5 Exception Objects • 1.1.6 Code Convention • 1.1.7 Javadoc
JAVA Comments • // single line comment • /* */ multi-line comment • Javadoc
JavaDoc and Javadoc Program • Javadoc 解析 Java 源文件中的声明和文档注释,并产生相应的 HTML 页(缺省),描述公有类、保护类、内部类、接口、构造函数、方法和域。 • 维护软件比开发软件花费的更多,如果软件很好的归档,维护工作将很容易。很多程序员在软件开发完后才归档,这是错误的。编码完成时归档也应该结束。 • 使用Javadoc可增强归档。 • 整个Java API的文档使用Javadoc形式。
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 */
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
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
Options to the javadoc program javadoc -private -author -d docs TwoInts.java