Multiple catch blocks 1• try block may contain code that throws different exception types.. Multiple catch blocks 2• If no exceptions are thrown in the try block, all catch blocks are
Trang 1Session 07
Package and Exceptions
(http://docs.oracle.com/javase/tutorial/essential/excepti
ons/index.html)
Trang 3• A package is a grouping of related classes,
interfaces, enumerations, and annotation types
providing access protection and name space
management
• Syntax to create a new package:
package [package name];
– This statement must be the first line in the source file – There can be only one package statement in each source file, and it applies to all types in the file.
Trang 4Using Packages Members
• To use a public package member from outside its package, we can:
– Refer to the member by its fully qualified name
graphics.Rectangle myRect = new graphics.Rectangle();
– Import the package member
import graphics.Rectangle;
… Rectangle myRectangle = new Rectangle();
– Import the member's entire package
import graphics.*;
… Rectangle myRectangle = new Rectangle();
Trang 5• When a program is executing something occurs that
is not quite normal from the point of view of the goal
at hand
• For example:
– a user might type an invalid filename;
– a file might contain corrupted data;
– a network link could fail;
– …
• Circumstances of this type are called exception
conditions in Java and are represented using objects
(All exceptions descend from the
java.lang.Throwable).
Trang 7Scanner in = new Scanner(System.in);
System.out.print(“Enter a whole number: ");
Trang 8Multiple catch blocks (1)
• try block may contain code that throws
different exception types This can even
happen if the block contains only a single line
of code, because a method is allowed to
throw different types to indicate different
kinds of trouble
Trang 9Multiple catch blocks (2)
• If no exceptions are thrown
in the try block, all catch blocks
are bypassed
Trang 10Multiple catch blocks (3)
• If an exception arises,
the first matching
catch block, if any, is
executed, and the
rest are skipped
Trang 11Multiple catch blocks (4)
int a;
int[] b = new int[3];
try {
Scanner in = new Scanner(System.in);
System.out.print(“Enter a whole number: ");
Trang 12The finally block (1)
• A try block may optionally have a finally block
associated with it
• The code within a finally block is guaranteed to
execute no matter what happens in the
try/catch code that precedes it
– The try block executes to completion without throwing any exceptions whatsoever.
– The try block throws an exception that is handled by one
of the catch blocks.
– The try block throws an exception that is not handled by
any of the catch blocks
Trang 13int a;
int[] b = new int[3];
try {
Scanner in = new Scanner(System.in);
System.out.print(“Enter a whole number: ");
a = in.nextInt();
b[a] = 5;
}catch (InputMismatchException e) {
System.out.println("Required integer!"); }catch(ArrayIndexOutOfBoundsException ex2){
System.out.println("Out of array index"); }finally{
System.out.println(“In finally block!” ); }
The finally block (2)
Trang 14Nesting of try/catch Blocks
• A try statement may be nested inside either the try
or catch block of another try statement
Trang 15Declaring Exceptions
• There is a way to call exception-throwing methods without enclosing the calls in try blocks A method declaration may end with the throws keyword,
followed by an exception type, or by multiple
exception types followed by commas
private void myMethod() throws IOException{
…
…
}
Trang 16Two Kinds of Exception
• Checked exception
– Must be handled by either the try-catch
mechanism or the throws-declaration mechanism
• Runtime exception
– The right time to deal with runtime exceptions is when you’re designing, developing, and debugging your code Since runtime exceptions should never
be thrown in finished code
Trang 17File f = new File("abc.txt");
try {
BufferedInputStream reader = new
BufferedInputStream(new FileInputStream(f));
} catch (FileNotFoundException ex) {
System.out.println("File not found!"); }
Checked exception
Trang 18The Exception Inheritance Hierarchy
Trang 19Throwing Exceptions
• The methods that you write can throw exceptions
• To throw your own exception, first decide whether the
exception should be checked at runtime Then choose the appropriate exception type.
• If you find a class whose name describes the situation you want to signal, use that class If you don’t, you’ll have to
create your own exception class.
Trang 20Creating Your Own Exception Classes (1)
• Decide whether you want a checked or a
runtime exception.
– Checked exceptions should extend
java.lang.Exception or one of its subclasses
– Runtime exceptions should extend
java.lang.RuntimeException or one of its
subclasses
Trang 21Creating Your Own Exception Classes (2)
//Your own exception class
class InvalidAge extends Exception{
public InvalidAge(String mes) {
super(mes);
}
}
Trang 22Creating Your Own Exception Classes (3)
//Throw exception in some method
Trang 23Creating Your Own Exception Classes (4)
//Using try-catch when this method is called
Trang 24Exceptions and Overriding
• When you extend a class and override a
method, the Java compiler insists that all
exception classes thrown by the new method must be the same as, or subclasses of, the
exception classes thrown by the original
method.
Trang 25• The intention is that assertions typically will be
enabled during development and disabled in the
field
Trang 26• If assertions are enabled at runtime (via a command-line
argument to the JVM), then Expression1 is evaluated.
– If its value is true, no further action is taken If its value is false, then
an AssertionError is thrown If Expression2 is present, it is passed into
the constructor of the AssertionError, where it is converted to a String and used as the error’s message.
Trang 27Assertions and Compilation
1.4 compiler
javac -source 1.4 UsefulApplication.java
– (If the flag was omitted, the 1.4 compiler treated
source code as if the assert keyword did not exist; thus assert could be used as an identifier.)
1.5 compiler
no longer necessary to compile with a -source flag
Trang 28Runtime Enabling of Assertions
• Assertions are disabled by default To enable assertions at runtime, use the –
enableassertions or -ea flag on the Java
command line, as in the following example:
java -ea UsefulApplication
Trang 29Using Assertions Sample
public static void main(String[] args){
int a = 5, b = 10;
assert a>b: "Bad";
System.out.println("OK");
}
Trang 30• Packages
• Exception Handling
• Multiple Handlers
• Code Finalization and Cleaning Up
• Custom Exception Classes
• Assertions