Download Exception

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Java I/O
Java I/O is based on input streams and output
streams.
All input and output are defined in the
Java IO package.
1
Input and Output
 There are three predefined standard streams:
Stream
Purpose
Default Device
System.in
reading input
Keyboard
System.out
writing output
Monitor
System.err
writing errors
monitor
 e.g
System.out.println writes to the console
2
Reading in using the Scanner class
 The code below creates an object of the Scanner class.
 What is returned is an Iterator that allows you read in from the
keyboard – the Scanner class implements the iterator interface.
Scanner scan = new Scanner(System.in) –
reads from the keyboard
Scanner scan = new Scanner(filename) –
reads in from an input file
3
I/O Streams
 A stream is a sequence of bytes that flows
from a source to a destination
 In a program, we read information from an input
stream
 and write information to an output stream
4
STREAMS of DATA
A program can manage multiple streams at a
time
The java.io package contains many classes to
read from:
a file, the keyboard, the console etc.
5
I/O Stream Categories
 The classes in the I/O package divide
 input and output streams into other categories
 An I/O stream is either a:
character stream, which deals with text data
Or A
byte stream, which deal with byte data(1 & 0’s)
6
I/O Streams
 An I/O stream is also either a
 data stream, which acts as either a source or
destination (keyboard or file)
 processing stream, which alters or manages
information in the data stream -
this stream will take characters and assemble them
into words
7
IO streams to and from the Console
 There are three standard I/O streams to and from the console:
 standard output – defined by System.out
 standard input – defined by System.in
 standard error – defined by System.err
 We use System.out when we execute System.out.println
statements
8
Types of input
 standard input – defined by System.in
 standard output – defined by System.out
 standard error – defined by System.err
 System.in reads characters in one by one.
 You attach System.in to another stream that
 will accumulate the characters into a word
9
Input/Output
 System.err implements the standard error stream.
 This is used to send error messages to you as the
program is executing. E.g. - to the console.
 E.g. The is the screen at the bottom of the Jgrasp
program where you can see your errors.
10
Streams
 Any source of input or destination for output is called a
stream.
 You must import into your program
import java.io
11
Exceptions
 Exceptions are thrown by a program, and
 may be caught and handled by another part of the
program.
 A program can therefore be separated into a
normal execution flow - your program runs
 and an exception execution flow – an exception stops the
program and may start another flow
12
Exception Not to Catch
public class Zero
{
public static void main (String[] args)
{
int numerator = 10;
int denominator = 0;
System.out.println (numerator / denominator);//
} // method main
} // class Zero // produces a division by 0 error
An error – division by 0 - represents a unrecoverable situation and
should not be caught.
13
Exception Handling
 A program can deal with an exception in one of three ways:
ignore it – (which is sometimes very tempting)
handle it where it occurs - preferred
handle it an another place in the program
 The manner in which an exception is processed is an important
design consideration.
14
Exception Handling
 If an exception is ignored by the program,
 the program will terminate and produce an appropriate message.
E.g
public static void main(String Args) throws IOException
{ …….
// reads in from a file and if an exception occurs
// it throws the exception so the program will close ……
}
The program will terminate. The Exception was not caught but
“ Thrown”
15
Throwing an Exception
 When the program terminates the call stack trace shows the
method call trail that leads to the line of code that caused the
problem. (line 40) E.g
java.lang.NullPointerException
at HPAirGUIApplet.init(HPAirGUIApplet.java:40)
// your code problem occurred at line 40 in the applet
// and the operation that is the culprits is at java 424 etc
at sun.applet.AppletPanel.run(AppletPanel.java:424)
at java.lang.Thread.run(Thread.java:619)
16
BETTER WAY TO HANDLE EXCEPTION
public String myMethod()
{
try { // calls trickyMethod()
……..
return trickyMethod(); // calls method and an exception
//may occur here
//
} catch ( IOException e ) // so catch it here and name it
{
// will print out the “bad data” (see next slide)
System.out.println (e.getMessage()“)
return null;
}}
17
trickyMethod throws the Exception back to the calling method
 trickyMethod can have an input exception:
public int trickyMethod() throws IOException
{
int result = readAnotherInt();// read in an int
if ( result < 0 ) throw new IOException( "bad data" );
return result;
}
//So if result is less than 0, an exception is thrown
//Execution goes back to the calling method ( myMethod())
//which prints out “bad data “ and then returns null – see
previous slide
18
Exceptions come is several flavors:
RuntimeExceptions, Errors, Checked and Unchecked.
Type codes used in describing Exceptions
Checked?
(declare throws?)
Letter
Type
Parent Class
R
Runtime
java.lang.RuntimeException
Error that can occur in almost any
code e.g. NullPointerException.
java.lang.Error
Serious error you really should not
try to catch, e.g.
OutOfMemoryError.
java.lang.Exception
Checked exceptions are required
by java to be handled e.g.
EOFException.
E
C
Error
Checked
Use
19
Class Exception – pre-defined java class
class Exception // defined in the java.io package
{
// will contain an error message to be printed out
private String message;// contains error message
// a string which describes the exception is sent and stored in
//“message”
public Exception (String message) // constructor
{
this.message = message; // user defined error message
}
// retrieve the String sent to the constructor to output
public String getMessage() {
return message:
}
20
(Class got Milk)
try
{
System.out.println("Enter number of donuts:");
donutCount = scan.nextInt();
System.out.println("Enter # of glasses of milk:");
milkCount =scan.nextInt();
if (milkCount < 1)
{
throw new Exception("Exception: No Milk!");
} // close try
{ more code }
catch(Exception e) // creates an object of Exception object “e”
{
// line below will output “Exception:NoMilk”)
System.out.println(e.getMessage()) // prints “Exception:NoMilk”
} // close catch
}
21
TRY - Catch
 Exception is a predefined class and the throws statement creates
a new object of the class Exception
 When the exception is thrown,
 the code in the surrounding try block stops executing
 and another portion of code  the catch block begins execution.
22
 The parameter to the catch :
catch (Exception e)
 is preceded by a class name that specifies what kind of
exception is thrown e.g.
 Exception, or
 FileNotFoundException
23
 In throws new Exception (“ Exception: No Milk”),
 the string “Exception: no milk” is an argument to the constructor
in the Exception class
 and is stored in an instance variable message so it can be
recovered with a getter method - e.getMessage().
24
Catching the Exception
 When the exception is thrown, execution goes to the catch
block:
catch ( Exception e)
{
System.out.println(e.getMessage());// prints error message
e.g; if we throw the exception with the string below
throw new Exception("Exception: No Milk!");
 So e.getMessage prints: “Exception: No Milk”
25
Throwing Exceptions back to calling method
public void eatPizza() throws StomachAcheException
(
….. Some code …..
if (ateTooMuch())
{
throw new StomachAcheException(“Ouch”);
…..
}
 When the StomachAcheException is thrown
 we exit from the eatPizza() method and
 go back to where the method was called from.
 If no exception is thrown, processing continues as normal to the
code after the catch block.
26
USER DEFINED EXCEPTION
class StomachAcheException // user defined exception
{
// will contain an error message to be printed out
private String message;// contains error message
// a string which describes the exception is sent and stored in //“message”
public Exception (String message) // constructor
{
this.message = message; // user defined error message
message = message + “ “ + “GET some alka seltzer”
}
// retrieve the String sent to the constructor to output
public String getMessage() {
return message: }
So the message contains “Ouch” + “GET some alka seltzer”
27
Types of Exceptions
 I .Errors:
 When a dynamic linking failure or other "hardware" failure in
the virtual machine occurs, the machine throws an Error.
 These are never thrown by the programmer. And the program
terminates
28
. Runtime Exceptions
 II. Runtime Exceptions:
 Subtypes of the RuntimeException class are unchecked
exceptions – they represent exceptions that occur during
runtime.
 “Unchecked “ means you are not required to catch them
But good coding practices demand that you do.
29
Exceptions and Exception Types
ClassNotFoundException
IOException
ArithmeticException
Exception
AWTException
NullPointerException
RuntimeException
IndexOutOfBoundsException
Object
Throwable
Several more classes
Several more classes
LinkageError
VirtualMachineError
Error
AWTError
Several more classes
30
Checked Exceptions
 An exception therefore is either
 checked or unchecked.
 A checked exception can only be thrown within a try
block
or
 within a method that is designated to throw that
exception.
31
Checked Exceptions
 The compiler will complain if a checked exception is
not handled appropriately.
 Checked exceptions are due to the environment which are
beyond the programmers control
 but to which the programmer must handle in their code
 E.g., EOFException (reading past the End of File),
FileNotFoundException
MalFormedURLException (an incorrectly coded URL)
32
Exception - Making your own
 To define a class representing a new checked exception,
( you can write your own!!)
 the code is
public class MyCheckedException extends Exception.
 Checked exceptions are checked by the compiler so you
have no choice but to handle them in the code
33
Unchecked Exceptions
 An unchecked exception (no try/catch required)
 results from programming errors.
 E.g. arithmetic exceptions such as dividing by zero
 ArithmeticException,
 ArrayIndexOutOfBounds Exception,
 NumberformatException,
 NullPointerException.
34
Unchecked Exceptions
 These do not require explicit handling,
 though good programmers do so.
 To define a class that will check these exceptions,
 Your new exception class must extend RunTime Exception .
35
Checked ExceptionsCatch or specify requirement
 Java requires that a method either
catch or
specify
all checked exceptions that are thrown within the scope of the
method. e.g.
Catch
 A method can catch an exception by providing an exception
handler for that type of exception. e .g.
 a try /catch block
36
Catch or specify requirement
Catch or specify requirement (con’d)
Specify
 If a method chooses not to catch an exception,
 the method must specify that it can throw that exception.
 E.g. in your method you can throw an exception without
catching it anywhere in the program .
 This is bad form!!
37
Runtime Exceptions - examples
 I . Exceptions can be thrown within the method
e.g The method handles the try/catch block
 II. Exceptions can be thrown indirectly by the method
through calls to other methods.
 E.g. Thus method1 calls method2 which throws an
exception.
 Whether method2 handles it or throws it is a design
issue.
38
Exception Propagation
 If it is not appropriate to handle the exception where it occurs,
 it can be handled at a higher level.
 The method will throw the exception in its header
39
Exceptions propagate
 Exceptions propagate up through the method calling hierarchy
 until they are caught and handled or
 or until they reach the outermost level.
40
Propagating Errors Up the Call Stack
public Method1
{
try
{
call method2;
} catch (exception) {
doErrorProcessing;
}
}
public Method2 throws exception // exception thrown to calling method
{
call method3;
}
public method3 throws exception // exception thrown back to calling method
{
call readFile; // this is where the exception can occur
}
41
The try Block writing to a file:
try{ /// all IO require checked exceptions
outFile = new PrintStream( new BufferedOutputStream (new
FileOutputStream("Out.txt")));
for (int i = 0; i < size; i++)
outFile.println("Value at: " + i + vector.elementAt(i));
} // close file
} catch (NegativeArraySizeException e) {
System.out.println(“Illegal argument “);
} catch (ArrayIndexOutOfBoundsException e) {
System.err.println("Caught ArrayIndexOutOfBoundsException: " +
e.getMessage());
} catch (IOException e) {
System.err.println("Caught IOException: " + e.getMessage());
}
42
IMPORTANT
Order of the listing of multiple exceptions:
 IF YOU PUT THE IOEXCEPTION FIRST IN THE ORDER,
 IF YOU HAVE A NegativeArraySizeException IT WILL BE
CAUGHT BY THE IOEXCEPTION .
 IOEXCEPTION WILL CATCH ALL EXCEPTIONS AND
YOU WILL NOT KNOW WHAT HAPPENED
 THIS WAS A QUESTION A GOOGLE INTERVIEWER
ASKED. See slide 40
43
The finally Clause
 A try statement can have an optional clause designated
by the reserved word finally.
 If no exception is generated, the statements in the finally
clause are executed after the statements in the try block
complete.
44
finally clauses
 Also, if an exception is generated,
 the statements in the finally clauses are executed after
the statements in the catch clause for that exception
completes.
45
 The statements within the finally block are always executed.
Why?

To provides a mechanism that allows your method to clean up after itself
regardless of what happens within the try block.
 Use the finally block to close files or release other system resources.
finally
{
System.out.println("Closing file");
outFile.close();
}
YOU MUST SPECIFICALLY CLOSE AN OUTPUT FILE, OR THE DATA
YOU WROTE TO IT IS LOST
46
ORDER OF EXCEPTIONS
 In this next example, the order of the catch clauses is according to
what you need to know.
 If you need to know if the file was not there, then you put that
first.
 If you put IOException first, then any IO exception could
occur
 and you would not know if the file was there.
47
Order of Exceptions
// exception CATCHES INCORRECT DATA
public void ReadFromFile
try
{ // read in an integer from a file
units = scanner.nextInt();
} // close try
catch (NumberFormatException exception)
{
System.out.println ("Error in input. Line ignored:");
System.out.println (units);
} // close catch
48
catch (FileNotFoundException exception)
{
System.out.println ("The file " + file + " was not found.");
} // close catch
catch (IOException exception){ // CATCHES ALL IO EXCEPTIONS
System.out.println ( “ IOexception – problem with file”)
System.out.println (exception);
}// close catch
catch (Exception e){ // CATCHES ALL EXCEPTIONS
System.out.println (exception);
}// close catch
finally
{
outFile.close();
e.printStackTrace();
}
49