When you use an input or output file that does not exist, what will happen? −The compiler insists that we tell it what the program should do in such case.

Similar presentations

Presentation on theme: "When you use an input or output file that does not exist, what will happen? −The compiler insists that we tell it what the program should do in such case."— Presentation transcript:

1
When you use an input or output file that does not exist, what will happen? −The compiler insists that we tell it what the program should do in such case. −When the input or output file doesn't exist, a FileNotFoundException can occur −In our next sample program, we take the easy way out and terminate the main method if the exception occurs. −To throw the exception, label the main method like this: public static void main(String[] args) throws FileNotFoundException −In the following sections, we will learn how to deal with exceptions in a more professional way. FileNotFoundException 1

2
Reads all lines of a file and sends them to the output file, preceded by line numbers Sample input file: Mary had a little lamb Whose fleece was white as snow. And everywhere that Mary went, The lamb was sure to go! Program produces the output file: /* 1 */ Mary had a little lamb /* 2 */ Whose fleece was white as snow. /* 3 */ And everywhere that Mary went, /* 4 */ The lamb was sure to go! Program can be used for numbering Java source files A Sample Program 2

5
There are two main aspects to exception handling: reporting and recovery −Point of reporting is usually far apart from the point of recovery Example: Assume that the get method of a class detects that a nonexistent element is being accessed. How the program decides what to do about this failure? −Should the user be asked to try a different operation? −Should the program be aborted after saving the user’s work? In Java exception handling provides a flexible mechanism for passing control from the point of error reporting to the point of competent recovery. When you detect an error condition, just throw an appropriate exception object to signal an exceptional condition and you are done. When an exception is thrown, method terminates immediately Execution continues with an exception handler Throwing Exceptions 5

6
public class BankAccount { public void withdraw(double amount) { if (amount > balance) { //what to do if someone trying to withdraw much money from a bank account } balance = balance - amount; }... } Throw an exception object to signal this exceptional condition −Java library provides many classes to signal all sorts of exceptional conditions −Look around for an exception type that might describe your situation In our example what about IllegalStateException or IllegalArgumentException: −Illegal state? Is the bank account is an illegal state for the witdraw operation? Not really −illegal argument value? It sounds more suitable Throwing Exceptions 6

9
 Checked oMajority of these exceptions occur when dealing with input and output ; i.e., IOException oWhen you throw these exceptions, compiler checks that you don't ignore them omust tell the compiler what you will to do about the exception when thrown. oThese exceptions are due to external circumstances that you cannot prevent  Unchecked oAll runtime exceptions are unchecked. oCompiler does not insist that your program be able to handle these conditions. oBut in your code you should test your references, your values, the format of your numbers before using them oRuntimeException (and its subclasses) or Error are an example NumberFormatException IllegalArgumentException NullPointerException oAnother Example of error: OutOfMemoryError Two types of exceptions : Checked and Unchecked 9

10
Categories aren't perfect: −Scanner.nextInt throws unchecked InputMismatchException −Checked exceptions would have been more appropriate because programmer cannot prevent users from entering incorrect input. −Designers made this choice to make the class easy to use for beginning programmers Deal with checked exceptions principally when programming with files and streams For example, use a Scanner to read a file String filename =...; FileReader reader = new FileReader(filename); Scanner in = new Scanner(reader); But, FileReader constructor can throw a FileNotFoundException Checked and Unchecked Exceptions 10

11
You have two choices: 1.Handle the exception as will be explained next slides 2.Or tell compiler that you are aware of this error and you want your method to be terminated when the exception occurs To declare that a method should be terminated when a checked exceptions occurs, use throws specifier so it can throw an exception public void read(String filename) throws FileNotFoundException { FileReader reader = new FileReader(filename); Scanner in = new Scanner(reader);... } −throws signals the caller of your method that it may encounter exception so caller needs to make a decision either to handle them or tell its caller that exception may be thrown. For multiple exceptions: public void read(String filename) throws IOException, ClassNotFoundException Checked and Unchecked Exceptions 11

12
Every exception should be handled somewhere in your program −No exception handler: an error message is printed and your program terminates −But you would not want a professionally written program to die because of some unexpected error. −There fore you should install exception handlers for all exceptions your program might throw. Install an exception handler with try/catch statement try block contains statements that may cause an exception catch clause contains handler for an exception type Catching Exceptions 12 try {... FileReader reader = new FileReader(filename); Scanner in = new Scanner(reader);... } catch (IOException exception) { exception.printStackTrace(); } catch (NumberFormatException exception) { System.out.println("Input was not a number"); }

15
Occasionally you need to take some action whether or not an exception is thrown. Exception terminates current method Danger: Can skip over essential code −For example, it is important to close a PrintWriter to ensure that all output is written to the file, or an exception may be thrown before closing a reader filer. Example: reader = new FileReader(filename); Scanner in = new Scanner(reader); readData(in); reader.close(); // May never get here Must execute reader.close () even if exception happens Use finally clause for code that must be executed "no matter what" The finally Clause 15

16
FileReader reader = new FileReader(filename); try { Scanner in = new Scanner(reader); readData(in); } finally { reader.close(); // if an exception occurs, finally clause is // also executed before exception is passed // to its handler } The finally Clause 16 Finally clause is executed when try block is exited in any of three ways: −After last statement of try block −After last statement of catch clause, if this try block caught an exception −When an exception was thrown in try block and not caught Recommendation: don't mix catch and finally clauses in same try block

17
You can design your own exception types – subclasses of Exception or RuntimeException if (amount > balance) { throw new InsufficientFundsException( "withdrawal of " + amount + " exceeds balance of " + balance); } Make it an unchecked exception – programmer could have avoided it by calling getBalance first Extend RuntimeException or one of its subclasses Supply two constructors 1.Default constructor 2.A constructor that accepts a message string describing reason for exception Designing Your Own Exception Types 17