Input and Output - PowerPoint PPT Presentation

1 / 33
About This Presentation
Title:

Input and Output

Description:

The parameter gives you a name for the exception that is caught. ... { System.err.println('Caught ArrayIndexOutOfBoundsException: ' e.getMessage ... – PowerPoint PPT presentation

Number of Views:47
Avg rating:3.0/5.0
Slides: 34
Provided by: cathyh9
Category:
Tags: caught | input | output

less

Transcript and Presenter's Notes

Title: Input and Output


1
Input and Output
  • Java I/O is based on input streams and output
    streams. All input and output are defined in the
    Java IO package.
  • There are three predefined standard streams
  • The print and println methods write to standard
    output. They are predefined methods in
    System.out, a part of the Java IO package.
    Streams must be used properly to ensure data is
    not lost.

Stream System.in System.out System.err
Purpose reading input writing output writing
errors
Default Device keyboard monitor monitor
2
I/O Streams
  • A stream is a sequence of bytes that flow from a
    source to a destination
  • In a program, we read information from an input
    stream and write information to an output stream
  • A program can manage multiple streams at a time
  • The java.io package contains many classes that
    allow us to define various streams with specific
    characteristics

3
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
  • byte stream, which deal with byte data
  • An I/O stream is also either a
  • data stream, which acts as either a source or
    destination
  • processing stream, which alters or manages
    information in the stream

4
Standard I/O
  • There are three standard I/O streams
  • standard input defined by System.in
  • standard output defined by System.out
  • standard error defined by System.err
  • We use System.out when we execute println
    statements
  • System.in is declared to be a generic InputStream
    reference, and therefore usually must be mapped
    to a more useful stream with specific
    characteristics. It reads characters one by one.

5
Input/Output
  • System.err implements the standard error stream.
    This is used to send error messages to a
    different place than your regular output as the
    program is executing. E.g. - to the console.
  • Simply put, any source of input or destination
    for output is called a stream. All IO comes from
    the API class libraries.
  • E.g. import java.io

6
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 and an exception execution
    flow.
  • An error division of 0 - is also represented as
    an object in Java, but usually represents a
    unrecoverable situation and should not be caught.

7
Exception
  • 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

8
Exception Handling
  • A program can deal with an exception in one of
    three ways
  • ignore it
  • handle it where it occurs
  • handle it an another place in the program
  • The manner in which an exception is processed is
    an important design consideration.

9
Exception Handling
  • If an exception is ignored by the program, the
    program will terminate and produce an appropriate
    message.
  • The message includes a call stack trace that
    indicates on which line the exception occurred.
  • The call stack trace also shows the method call
    trail that lead to the execution of the offending
    line. E.g
  • java.lang.NullPointerException at
    HPAirGUIApplet.init(HPAirGUIApplet.java40)
    at sun.applet.AppletPanel.run(AppletPanel.java42
    4) at java.lang.Thread.run(Thread.java619)

10
Exception
  • The basic syntax to handle an Exception looks
    like this
  • public String myMethod()
  • try
  • return trickyMethod()
  • catch ( IOException e )
  • return null

11
Syntax for exceptions
  • The basic Syntax to generate an exception looks
    like this
  • public String trickyMethod() throws IOException
  • int result readAnotherChar()
  • if ( result lt 0 ) throw new IOException( "bad
    data" )
  • return result

12
Exception come is several flavours
RuntimeExceptions, Errors, Checked and Unchecked.
13
Exceptions
  • You throw the exception in a try block and catch
    the exception in another part of the program.
    Syntax
  • try
  • Code_to_Try
  • Maybe throw an exception
  • More Code
  • If milkCount lt 1)
  • throw new Exception(Exception No milk!)

14
Class Exception
  • class Exception
  • private String message
  • public Exception (String NewMessage)
  • message NewMessage
  • public String getMessage()
  • return message

15
  • try
  • System.out.println("Enter number of donuts")
  • donutCount scan.nextInt()
  •   System.out.println("Enter of glasses of
    milk")
  • milkCount scan.nextInt()
  • if (milkCount lt 1)
  • throw new Exception("Exception No
    Milk!")
  • // close try
  •   more code
  • catch(Exception e)
  • System.out.println(e.getMessage())
  • System.out.println(Go buy some Milk)
  • // close catch See GotMilk.java

16
TRY - Catch
  • Exception is a predefined class and the throws
    statement creates a new object of the class
    Exception and throws it.
  • When the exception is thrown, the code in the
    surrounding try block stops executing and another
    portion of code,know as catch block begins
    execution.
  • The catch block looks a little like a method
    definition but it is not.

17
Exceptions
  • The parameter to the catch
  • catch (Exception e)
  • Is preceded by a class name that specifies what
    kind of exception the catch block can catch ,
    here it is Exception
  • The parameter gives you a name for the exception
    that is caught.
  • In throws new Exception ( Get Milk), the string
    GetMilk is an argument to the constructor in
    the Exception class and is stored in an instance
    variable message so it can be recovered in the
    catch clause.

18
Catching the Exception
  • When the exception is thrown, execution goes to
    the catch block
  • catch ( Exception e)
  • System.out.println(e.getMessage())
  • Every exception object has a method called
    e.getMessage() which contains the string used in
    the
  • throw new Exception("Exception No Milk!")
  • So that e.getMessage prints Exception No Milk
  • If no exception is thrown, processing continues
    to the code after the catch block.

19
Exceptions
  • public void eatPizza() throws StomachAcheException
  • (
  • ..
  • if (ateTooMuch())
  • throw new StomachAcheException(Ouch)
  • ..
  • As soon as the exception is thrown, we exit from
    the method.
  • When the StomachAcheException is thrown we exit
    from the eatPizza() method and go back to where
    the method was called from.

20
Types of Exceptions
  • Errors
  • When a dynamic linking failure or some other
    "hard" failure in the virtual machine occurs, the
    virtual machine throws an Error. These are never
    thrown by the programmer.
  • Runtime Exceptions
  • Subtypes of the RuntimeException class are
    unchecked exceptions they represent exceptions
    that occur within the Java virtual machine
    (during runtime). This means you are not
    required to have a try/catch block
  • Exceptions
  • All other exceptions, subtypes of the Exception
    class are checked. Which means you MUST have a
    try/catch block or it will not compile.

21
Exceptions and Exception Types
22
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.
  • 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 an intelligent response can be made
  • E.g., EOFException(reading past the End of File),
    FileNotFoundException
  • MalFormedURLException(an incorrectly listed
    URL)

23
Exception
  • To define a class representing a new checked
    exception, the code is
  • public class MyCheckedException extends
    Exception.
  • Checked exceptions are checked by the compiler
    e.g. You can not read from a file without using
    a try/catch block.

24
Unchecked Exceptions
  • An unchecked exception (no try/catch required)
    result from programming errors. E.g. arithmetic
    exceptions such as dividing by zero
  • ArithmeticException,
  • ArrayIndexOutOfBounds Exception,
  • NumberformatException,
  • NullPointerException.
  • These do not require explicit handling, though it
    is good to do so.
  • To define a class that will check these
    exceptions, you must extend RunTime Exception .

25
Catching an Exception
  • Catch or specify requirement
  • Java requires that a method either catch or
    specify all checked exceptions that can be thrown
    within the scope of the method.
  • Catch
  • A method can catch an exception by providing an
    exception handler for that type of exception.e.g
    try /catch block
  • Specify
  • If a method chooses not to catch an exception,
    the method must specify that it can throw that
    exception. E.g. in the main method
  • public static void main (String args)
    throws IOException
  • which means that the program will terminate if an
    exception is thrown.

26
Runtime Exceptions
  • Exceptions that can be thrown within the scope
    of the method
  • Exceptions that are thrown directly by the method
    with Java's throw statement. The method handles
    the try/catch block
  • Exceptions that are thrown indirectly by the
    method through calls to other methods. The
    calling method handles the try/catch block
  • Thus method1 calls method2 which throws an
    exception. Whether method2 handles it or throws
    it is a design issue.

27
Exception Propagation
  • If it is not appropriate to handle the exception
    where it occurs, it can be handled at a higher
    level.
  • Exceptions propagate up through the method
    calling hierarchy until they are caught and
    handled or until they reach the outermost level.
  • It happens when the exception object bubbles up
    through the call stack until an appropriate
    exception handler is found.
  • The handler catches the exception. See
    Propagation_Demo.java

28
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 to calling method
  • call readFile // this is where the
    exception can occur
  •  

29
Catching and Handling File Exceptions
  • The try Block writing to a file
  • try /// This is a checked exception
  • outFile new PrintStream( new
    BufferedOutputStream (new FileOutputStream("Out.tx
    t")))
  • for (int i 0 i lt size i)
  • outFile.println("Value at " i
    victor.elementAt(i))
  • // close file
  • catch (FileNotFoundException e)
  • System.out.println(File not found )
  • catch (ArrayIndexOutOfBoundsException e)
  • System.err.println("Caught ArrayIndexOutOfBoun
    dsException " e.getMessage())
  • catch (IOException e)
  • System.err.println("Caught IOException "
    e.getMessage())

30
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.
  • Also, if an exception is generated, the
    statements in the finally clause are executed
    after the statements in the appropriate catch
    clause completes.

31
  • 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()

32
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.
  • // 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
  • inFile.close() // close try
    for file

33
catch (FileNotFoundException exception)
System.out.println ("The file " file "
was not found.") // close catch
catch (IOException exception)
System.out.println (exception) // close
catch catch (Exception e)
System.out.println (exception) // close
catch finally
outFile.close() e.printStackTrace()
Write a Comment
User Comments (0)
About PowerShow.com