SlideShare a Scribd company logo
Week 12
Exceptions and
File I/O
Copyright Warning
                             COMMONWEALTH OF AUSTRALIA
                               Copyright Regulations 1969
                                                     WARNING
 This material has been copied and communicated to you by or
    on behalf of Bond University pursuant to Part VB of the
                  Copyright Act 1968 (the Act).
The material in this communication may be subject to copyright
 under the Act. Any further copying or communication of this
  material by you may be the subject of copyright protection
                        under the Act.


Do not remove this notice.

© 2004 Pearson Addison-Wesley. All rights reserved             10-2
Methods Return Values
• We have seen that programs are usually broken
  into modules:
        Classes provide a set of attributes that a collection of
         “things” have in common, even if they have different
         values
        Methods provide access to class attributes
        Methods also allow a large problem to be broken into
         several sub-task, and each method provides one sub-task
• Methods are passed input parameters
• Methods work on their inputs, possibly call other
  methods, and can return one value to their caller
• But what do we do if there isn't a value to return?


© 2004 Pearson Addison-Wesley. All rights reserved           10-3
Consider the Scanner Class
• The Scanner Class reads input from the user.
• Actually, it reads lines of text from somewhere,
  and converts the text into something else, e.g.
        scan.nextInt() reads in the next integer from the line
         of input text
• So, we can do this:
       System.out.print(“What is your age: ”);
       age= scan.nextInt();
• What happens when the user types a word instead
  of a set of digits?
• What int value will the nextInt() method
  return?
        We can't use a specific int value to indicate error. Why
         not?
© 2004 Pearson Addison-Wesley. All rights reserved              10-4
We Need Two Types of Return Values
• We can't return a normal value to the caller of a
  method, yet we want them to know that something
  went wrong
• Many languages, including Java, allow a method to
  return two types of things back to the caller:
        A return value, which is what usually happens, or
        An Exception, which informs the method caller that there
         is no return value, and something went wrong
• A method can only send back one of these things,
  not both
• A method caller can choose to receive either or
  both of these things, or ignore either or both too

© 2004 Pearson Addison-Wesley. All rights reserved            10-5
Exceptions: Visually


 age= scan.nextInt();
                                                         nextInt()



                                                     return(num);


                                                     Throw Exception;




© 2004 Pearson Addison-Wesley. All rights reserved                      10-6
Exceptions
• An exception is an object that describes an
  unusual or erroneous situation

• Exceptions are thrown by a program, and may be
  caught and handled by another part of the
  program

• A program can be separated into a normal
  execution flow and an exception execution flow

• Java also has a related thing called an error

• An error is also represented as an object in Java,
  but usually represents a unrecoverable situation
  and should not be caught
© 2004 Pearson Addison-Wesley. All rights reserved   10-7
Exception Handling
• Java has a predefined set of exceptions and errors
  that can occur during execution
        And you can make your own up to suit your situation

• 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
• Try to handle an exception where you can recover
  from it
© 2004 Pearson Addison-Wesley. All rights reserved             10-8
Exception Handling
  • If an exception is ignored by the program, the
    program will terminate abnormally and produce
    an appropriate message

  • The message includes a call stack trace that:
           indicates the line on which the exception occurred

           shows the method call trail that lead to the attempted
            execution of the offending line




© 2004 Pearson Addison-Wesley. All rights reserved                   10-9
Ignoring an Exception
          System.out.print(“What is your age: ”);
          age= scan.nextInt();



          What is your age: none of your business

          InputMismatchException: next item is not an
            integer at Scanner.nextInt()



          (program stops)




© 2004 Pearson Addison-Wesley. All rights reserved      10-10
Outline
                               Exception Handling
                               The try-catch Statement
                               Exception Classes
                               I/O Exceptions




© 2004 Pearson Addison-Wesley. All rights reserved       10-11
Catching Exceptions: The try Statement
• To handle an exception in a program, the line that
  throws the exception is executed within a try block

• A try block is followed by one or more catch
  clauses

• Each catch clause has an associated exception
  type and is called an exception handler

• When an exception occurs, processing continues
  at the first catch clause that matches the
  exception type



© 2004 Pearson Addison-Wesley. All rights reserved   10-12
An Example
       try
       {
              System.out.print("What is your age: ");
              age= scan.nextInt();
       }
       catch (InputMismatchException e)
       {
           System.out.println("You didn't type a number");
           System.out.println("Java says: " + e);
       }


• Note that e is an object declared as part of the catch
  line, and it is an object of the InputMismatchException
  class
© 2004 Pearson Addison-Wesley. All rights reserved           10-13
Class Question
       try
       {
              System.out.print("What is your age: ");
              age= scan.nextInt();
       }
       catch (InputMismatchException e)
       {
           System.out.println("You didn't type a number");
           System.out.println("Java says: " + e);
       }


• How do we modify the above so that it loops until the
  user does enter an integer value?

© 2004 Pearson Addison-Wesley. All rights reserved           10-14
The finally Clause
• A try statement can have an optional clause
  following the catch clauses, designated by the
  reserved word finally

• The statements in the finally clause always are
  executed

• If no exception is generated, the statements in the
  finally clause are executed after the statements in
  the try block complete

• If an exception is generated, the statements in the
  finally clause are executed after the statements in
  the appropriate catch clause complete

© 2004 Pearson Addison-Wesley. All rights reserved   10-15
Input/Output and Exceptions
• Let's examine issues related to exceptions and I/O

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

• Streams can be connected to the keyboard, the
  terminal, or to/from files on the computer, and
  even network connections

© 2004 Pearson Addison-Wesley. All rights reserved   10-16
Standard I/O
• There are three standard I/O streams:
        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 println
  statements
• System.out and System.err typically represent a
  particular window on the monitor screen
• System.in typically represents keyboard input,
  which we've used many times with Scanner
  objects

© 2004 Pearson Addison-Wesley. All rights reserved   10-17
The IOException Class
• Operations performed by some I/O classes may
  throw an IOException
        A file might not exist

        Even if the file exists, a program may not be able to find it

        The file might not contain the kind of data we expect




© 2004 Pearson Addison-Wesley. All rights reserved                10-18
Writing Text Files
• Java provides a whole pile of classes to deal with
  I/O. In fact, there’s a complex hierarchy of classes
• We are going to look at how to get access to text
  files, in a way that allows you to use println()
  and friends
• Text files are files made up entirely of plain text.
  They could be:
        Plain text .txt files

        Comma-separated value .csv files

        Web documents , i.e. .html files


© 2004 Pearson Addison-Wesley. All rights reserved   10-19
Writing Text Files
• In order to use a text file, we must open it for
  writing. This gives us exclusive access to the file:
         PrintWriter outFile;
         String filename= “myfile.txt”;
         try
         {
           outFile= new PrintWriter(
                  new BufferedWriter(
                    new FileWriter(filename)));
         }

© 2004 Pearson Addison-Wesley. All rights reserved   10-20
Writing Text Files
• Opening a file can throw an IOException for many
  reasons, so we must try { … } catch{ … } it
• Once the file is open, we can use the outFile
  object (of class PrintWriter) as we would use
  System.out:
            outFile.println(“Hello, how are you?”);

            outFile.print(“The variable x is ” + x);

• We must close the file when we’re finished, to let
  other users or programs access the file:
        outFile.close();


© 2004 Pearson Addison-Wesley. All rights reserved     10-21
Reading Text Files
• Just as with writing a text file, we must open a file
  for reading. This stops other users or programs
  from trying to write to the file at the same time
    Scanner inScan;
    String filename= “myfile.txt”;
    try
    {
       inScan= new Scanner(
                   new FileReader(filename));
    }
• And of course a catch { … } clause

© 2004 Pearson Addison-Wesley. All rights reserved   10-22
Reading Text Files
• After that, you can use the nextInt(),
  nextDouble(), nextline() methods on the
  inScan object
• The Scanner class also has a set of methods that
  allow you to find out if there is any input of a
  certain type left:
        inScan.hasNextLine()
        inScan.hasNextInt()
        inScan.hasNextDouble()
• We also need to close the input file once we are
  done with it
        inScan.close()


© 2004 Pearson Addison-Wesley. All rights reserved   10-23

More Related Content

Viewers also liked

Notes5
Notes5Notes5
Notes5
hccit
 
University partnerships programs email
University partnerships programs emailUniversity partnerships programs email
University partnerships programs email
hccit
 
Week03
Week03Week03
Week03
hccit
 
10 ict gm_game_assignment_2013
10 ict gm_game_assignment_201310 ict gm_game_assignment_2013
10 ict gm_game_assignment_2013
hccit
 
3 d modelling_task_sheet_2014_yr12
3 d modelling_task_sheet_2014_yr123 d modelling_task_sheet_2014_yr12
3 d modelling_task_sheet_2014_yr12
hccit
 
Week05
Week05Week05
Week05
hccit
 
Week04
Week04Week04
Week04
hccit
 
Notes2
Notes2Notes2
Notes2
hccit
 

Viewers also liked (8)

Notes5
Notes5Notes5
Notes5
 
University partnerships programs email
University partnerships programs emailUniversity partnerships programs email
University partnerships programs email
 
Week03
Week03Week03
Week03
 
10 ict gm_game_assignment_2013
10 ict gm_game_assignment_201310 ict gm_game_assignment_2013
10 ict gm_game_assignment_2013
 
3 d modelling_task_sheet_2014_yr12
3 d modelling_task_sheet_2014_yr123 d modelling_task_sheet_2014_yr12
3 d modelling_task_sheet_2014_yr12
 
Week05
Week05Week05
Week05
 
Week04
Week04Week04
Week04
 
Notes2
Notes2Notes2
Notes2
 

Similar to Week12

Week10style
Week10styleWeek10style
Week10style
hccit
 
Cso gaddis java_chapter12
Cso gaddis java_chapter12Cso gaddis java_chapter12
Cso gaddis java_chapter12
mlrbrown
 
Exception handling
Exception handlingException handling
Exception handling
Ravi Sharda
 
Exception Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception HandlingException Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception Handling
AboMohammad10
 
Java căn bản - Chapter8
Java căn bản - Chapter8Java căn bản - Chapter8
Java căn bản - Chapter8
Vince Vo
 

Similar to Week12 (20)

Week10style
Week10styleWeek10style
Week10style
 
Cso gaddis java_chapter12
Cso gaddis java_chapter12Cso gaddis java_chapter12
Cso gaddis java_chapter12
 
Lecture 1 Try Throw Catch.pptx
Lecture 1 Try Throw Catch.pptxLecture 1 Try Throw Catch.pptx
Lecture 1 Try Throw Catch.pptx
 
Eo gaddis java_chapter_10_5e
Eo gaddis java_chapter_10_5eEo gaddis java_chapter_10_5e
Eo gaddis java_chapter_10_5e
 
Programming with C++
Programming with C++Programming with C++
Programming with C++
 
Exception handling
Exception handlingException handling
Exception handling
 
Icom4015 lecture10-f16
Icom4015 lecture10-f16Icom4015 lecture10-f16
Icom4015 lecture10-f16
 
Exception handling
Exception handlingException handling
Exception handling
 
Java: Exception
Java: ExceptionJava: Exception
Java: Exception
 
Role of .NET in Exception Handling
Role of .NET in Exception HandlingRole of .NET in Exception Handling
Role of .NET in Exception Handling
 
Exception handling
Exception handlingException handling
Exception handling
 
Lecture 3.1.1 Try Throw Catch.pptx
Lecture 3.1.1 Try Throw Catch.pptxLecture 3.1.1 Try Throw Catch.pptx
Lecture 3.1.1 Try Throw Catch.pptx
 
Exception handling
Exception handlingException handling
Exception handling
 
UNIT III 2021R.pptx
UNIT III 2021R.pptxUNIT III 2021R.pptx
UNIT III 2021R.pptx
 
UNIT III 2021R.pptx
UNIT III 2021R.pptxUNIT III 2021R.pptx
UNIT III 2021R.pptx
 
Exception Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception HandlingException Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception Handling
 
Debugging java deployments_2
Debugging java deployments_2Debugging java deployments_2
Debugging java deployments_2
 
Chapter 8 - Exceptions and Assertions Edit summary
Chapter 8 - Exceptions and Assertions  Edit summaryChapter 8 - Exceptions and Assertions  Edit summary
Chapter 8 - Exceptions and Assertions Edit summary
 
Java căn bản - Chapter8
Java căn bản - Chapter8Java căn bản - Chapter8
Java căn bản - Chapter8
 
OOPs & C++(UNIT 5)
OOPs & C++(UNIT 5)OOPs & C++(UNIT 5)
OOPs & C++(UNIT 5)
 

More from hccit

Snr ipt 10_syll
Snr ipt 10_syllSnr ipt 10_syll
Snr ipt 10_syll
hccit
 
Snr ipt 10_guide
Snr ipt 10_guideSnr ipt 10_guide
Snr ipt 10_guide
hccit
 
3 d modelling_task_sheet_2014_yr11
3 d modelling_task_sheet_2014_yr113 d modelling_task_sheet_2014_yr11
3 d modelling_task_sheet_2014_yr11
hccit
 
10 ict photoshop_proj_2014
10 ict photoshop_proj_201410 ict photoshop_proj_2014
10 ict photoshop_proj_2014
hccit
 
Photoshop
PhotoshopPhotoshop
Photoshop
hccit
 
Flash
FlashFlash
Flash
hccit
 
Griffith sciences pathway programs overview
Griffith sciences pathway programs overviewGriffith sciences pathway programs overview
Griffith sciences pathway programs overview
hccit
 
Griffith info tech brochure
Griffith info tech brochureGriffith info tech brochure
Griffith info tech brochure
hccit
 
Pm sql exercises
Pm sql exercisesPm sql exercises
Pm sql exercises
hccit
 
Repairs questions
Repairs questionsRepairs questions
Repairs questions
hccit
 
Movies questions
Movies questionsMovies questions
Movies questions
hccit
 
Australian birds questions
Australian birds questionsAustralian birds questions
Australian birds questions
hccit
 
Section b
Section bSection b
Section b
hccit
 
Section a
Section aSection a
Section a
hccit
 
Ask manual rev5
Ask manual rev5Ask manual rev5
Ask manual rev5
hccit
 
Case study report mj
Case study report mjCase study report mj
Case study report mj
hccit
 
Mj example case_study_layout_intro_completedq
Mj example case_study_layout_intro_completedqMj example case_study_layout_intro_completedq
Mj example case_study_layout_intro_completedq
hccit
 
Case study plan mj
Case study plan mjCase study plan mj
Case study plan mj
hccit
 

More from hccit (20)

Snr ipt 10_syll
Snr ipt 10_syllSnr ipt 10_syll
Snr ipt 10_syll
 
Snr ipt 10_guide
Snr ipt 10_guideSnr ipt 10_guide
Snr ipt 10_guide
 
3 d modelling_task_sheet_2014_yr11
3 d modelling_task_sheet_2014_yr113 d modelling_task_sheet_2014_yr11
3 d modelling_task_sheet_2014_yr11
 
10 ict photoshop_proj_2014
10 ict photoshop_proj_201410 ict photoshop_proj_2014
10 ict photoshop_proj_2014
 
Photoshop
PhotoshopPhotoshop
Photoshop
 
Flash
FlashFlash
Flash
 
Griffith sciences pathway programs overview
Griffith sciences pathway programs overviewGriffith sciences pathway programs overview
Griffith sciences pathway programs overview
 
Griffith info tech brochure
Griffith info tech brochureGriffith info tech brochure
Griffith info tech brochure
 
Pm sql exercises
Pm sql exercisesPm sql exercises
Pm sql exercises
 
Repairs questions
Repairs questionsRepairs questions
Repairs questions
 
Movies questions
Movies questionsMovies questions
Movies questions
 
Australian birds questions
Australian birds questionsAustralian birds questions
Australian birds questions
 
Section b
Section bSection b
Section b
 
B
BB
B
 
A
AA
A
 
Section a
Section aSection a
Section a
 
Ask manual rev5
Ask manual rev5Ask manual rev5
Ask manual rev5
 
Case study report mj
Case study report mjCase study report mj
Case study report mj
 
Mj example case_study_layout_intro_completedq
Mj example case_study_layout_intro_completedqMj example case_study_layout_intro_completedq
Mj example case_study_layout_intro_completedq
 
Case study plan mj
Case study plan mjCase study plan mj
Case study plan mj
 

Recently uploaded

Recently uploaded (20)

UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
 
IoT Analytics Company Presentation May 2024
IoT Analytics Company Presentation May 2024IoT Analytics Company Presentation May 2024
IoT Analytics Company Presentation May 2024
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
 
Exploring UiPath Orchestrator API: updates and limits in 2024 🚀
Exploring UiPath Orchestrator API: updates and limits in 2024 🚀Exploring UiPath Orchestrator API: updates and limits in 2024 🚀
Exploring UiPath Orchestrator API: updates and limits in 2024 🚀
 
Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
 
НАДІЯ ФЕДЮШКО БАЦ «Професійне зростання QA спеціаліста»
НАДІЯ ФЕДЮШКО БАЦ  «Професійне зростання QA спеціаліста»НАДІЯ ФЕДЮШКО БАЦ  «Професійне зростання QA спеціаліста»
НАДІЯ ФЕДЮШКО БАЦ «Професійне зростання QA спеціаліста»
 
Speed Wins: From Kafka to APIs in Minutes
Speed Wins: From Kafka to APIs in MinutesSpeed Wins: From Kafka to APIs in Minutes
Speed Wins: From Kafka to APIs in Minutes
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
 
ODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User GroupODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User Group
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
 
"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
 

Week12

  • 2. Copyright Warning COMMONWEALTH OF AUSTRALIA Copyright Regulations 1969 WARNING This material has been copied and communicated to you by or on behalf of Bond University pursuant to Part VB of the Copyright Act 1968 (the Act). The material in this communication may be subject to copyright under the Act. Any further copying or communication of this material by you may be the subject of copyright protection under the Act. Do not remove this notice. © 2004 Pearson Addison-Wesley. All rights reserved 10-2
  • 3. Methods Return Values • We have seen that programs are usually broken into modules:  Classes provide a set of attributes that a collection of “things” have in common, even if they have different values  Methods provide access to class attributes  Methods also allow a large problem to be broken into several sub-task, and each method provides one sub-task • Methods are passed input parameters • Methods work on their inputs, possibly call other methods, and can return one value to their caller • But what do we do if there isn't a value to return? © 2004 Pearson Addison-Wesley. All rights reserved 10-3
  • 4. Consider the Scanner Class • The Scanner Class reads input from the user. • Actually, it reads lines of text from somewhere, and converts the text into something else, e.g.  scan.nextInt() reads in the next integer from the line of input text • So, we can do this: System.out.print(“What is your age: ”); age= scan.nextInt(); • What happens when the user types a word instead of a set of digits? • What int value will the nextInt() method return?  We can't use a specific int value to indicate error. Why not? © 2004 Pearson Addison-Wesley. All rights reserved 10-4
  • 5. We Need Two Types of Return Values • We can't return a normal value to the caller of a method, yet we want them to know that something went wrong • Many languages, including Java, allow a method to return two types of things back to the caller:  A return value, which is what usually happens, or  An Exception, which informs the method caller that there is no return value, and something went wrong • A method can only send back one of these things, not both • A method caller can choose to receive either or both of these things, or ignore either or both too © 2004 Pearson Addison-Wesley. All rights reserved 10-5
  • 6. Exceptions: Visually age= scan.nextInt(); nextInt() return(num); Throw Exception; © 2004 Pearson Addison-Wesley. All rights reserved 10-6
  • 7. Exceptions • An exception is an object that describes an unusual or erroneous situation • Exceptions are thrown by a program, and may be caught and handled by another part of the program • A program can be separated into a normal execution flow and an exception execution flow • Java also has a related thing called an error • An error is also represented as an object in Java, but usually represents a unrecoverable situation and should not be caught © 2004 Pearson Addison-Wesley. All rights reserved 10-7
  • 8. Exception Handling • Java has a predefined set of exceptions and errors that can occur during execution  And you can make your own up to suit your situation • 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 • Try to handle an exception where you can recover from it © 2004 Pearson Addison-Wesley. All rights reserved 10-8
  • 9. Exception Handling • If an exception is ignored by the program, the program will terminate abnormally and produce an appropriate message • The message includes a call stack trace that:  indicates the line on which the exception occurred  shows the method call trail that lead to the attempted execution of the offending line © 2004 Pearson Addison-Wesley. All rights reserved 10-9
  • 10. Ignoring an Exception System.out.print(“What is your age: ”); age= scan.nextInt(); What is your age: none of your business InputMismatchException: next item is not an integer at Scanner.nextInt() (program stops) © 2004 Pearson Addison-Wesley. All rights reserved 10-10
  • 11. Outline Exception Handling The try-catch Statement Exception Classes I/O Exceptions © 2004 Pearson Addison-Wesley. All rights reserved 10-11
  • 12. Catching Exceptions: The try Statement • To handle an exception in a program, the line that throws the exception is executed within a try block • A try block is followed by one or more catch clauses • Each catch clause has an associated exception type and is called an exception handler • When an exception occurs, processing continues at the first catch clause that matches the exception type © 2004 Pearson Addison-Wesley. All rights reserved 10-12
  • 13. An Example try { System.out.print("What is your age: "); age= scan.nextInt(); } catch (InputMismatchException e) { System.out.println("You didn't type a number"); System.out.println("Java says: " + e); } • Note that e is an object declared as part of the catch line, and it is an object of the InputMismatchException class © 2004 Pearson Addison-Wesley. All rights reserved 10-13
  • 14. Class Question try { System.out.print("What is your age: "); age= scan.nextInt(); } catch (InputMismatchException e) { System.out.println("You didn't type a number"); System.out.println("Java says: " + e); } • How do we modify the above so that it loops until the user does enter an integer value? © 2004 Pearson Addison-Wesley. All rights reserved 10-14
  • 15. The finally Clause • A try statement can have an optional clause following the catch clauses, designated by the reserved word finally • The statements in the finally clause always are executed • If no exception is generated, the statements in the finally clause are executed after the statements in the try block complete • If an exception is generated, the statements in the finally clause are executed after the statements in the appropriate catch clause complete © 2004 Pearson Addison-Wesley. All rights reserved 10-15
  • 16. Input/Output and Exceptions • Let's examine issues related to exceptions and I/O • 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 simultaneously • Streams can be connected to the keyboard, the terminal, or to/from files on the computer, and even network connections © 2004 Pearson Addison-Wesley. All rights reserved 10-16
  • 17. Standard I/O • There are three standard I/O streams:  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 println statements • System.out and System.err typically represent a particular window on the monitor screen • System.in typically represents keyboard input, which we've used many times with Scanner objects © 2004 Pearson Addison-Wesley. All rights reserved 10-17
  • 18. The IOException Class • Operations performed by some I/O classes may throw an IOException  A file might not exist  Even if the file exists, a program may not be able to find it  The file might not contain the kind of data we expect © 2004 Pearson Addison-Wesley. All rights reserved 10-18
  • 19. Writing Text Files • Java provides a whole pile of classes to deal with I/O. In fact, there’s a complex hierarchy of classes • We are going to look at how to get access to text files, in a way that allows you to use println() and friends • Text files are files made up entirely of plain text. They could be:  Plain text .txt files  Comma-separated value .csv files  Web documents , i.e. .html files © 2004 Pearson Addison-Wesley. All rights reserved 10-19
  • 20. Writing Text Files • In order to use a text file, we must open it for writing. This gives us exclusive access to the file: PrintWriter outFile; String filename= “myfile.txt”; try { outFile= new PrintWriter( new BufferedWriter( new FileWriter(filename))); } © 2004 Pearson Addison-Wesley. All rights reserved 10-20
  • 21. Writing Text Files • Opening a file can throw an IOException for many reasons, so we must try { … } catch{ … } it • Once the file is open, we can use the outFile object (of class PrintWriter) as we would use System.out: outFile.println(“Hello, how are you?”); outFile.print(“The variable x is ” + x); • We must close the file when we’re finished, to let other users or programs access the file:  outFile.close(); © 2004 Pearson Addison-Wesley. All rights reserved 10-21
  • 22. Reading Text Files • Just as with writing a text file, we must open a file for reading. This stops other users or programs from trying to write to the file at the same time Scanner inScan; String filename= “myfile.txt”; try { inScan= new Scanner( new FileReader(filename)); } • And of course a catch { … } clause © 2004 Pearson Addison-Wesley. All rights reserved 10-22
  • 23. Reading Text Files • After that, you can use the nextInt(), nextDouble(), nextline() methods on the inScan object • The Scanner class also has a set of methods that allow you to find out if there is any input of a certain type left:  inScan.hasNextLine()  inScan.hasNextInt()  inScan.hasNextDouble() • We also need to close the input file once we are done with it  inScan.close() © 2004 Pearson Addison-Wesley. All rights reserved 10-23