SlideShare a Scribd company logo
1 of 23
Download to read offline
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
Notes5hccit
 
University partnerships programs email
University partnerships programs emailUniversity partnerships programs email
University partnerships programs emailhccit
 
Week03
Week03Week03
Week03hccit
 
10 ict gm_game_assignment_2013
10 ict gm_game_assignment_201310 ict gm_game_assignment_2013
10 ict gm_game_assignment_2013hccit
 
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_yr12hccit
 
Week05
Week05Week05
Week05hccit
 
Week04
Week04Week04
Week04hccit
 
Notes2
Notes2Notes2
Notes2hccit
 

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
Week10stylehccit
 
Cso gaddis java_chapter12
Cso gaddis java_chapter12Cso gaddis java_chapter12
Cso gaddis java_chapter12mlrbrown
 
Lecture 1 Try Throw Catch.pptx
Lecture 1 Try Throw Catch.pptxLecture 1 Try Throw Catch.pptx
Lecture 1 Try Throw Catch.pptxVishuSaini22
 
Eo gaddis java_chapter_10_5e
Eo gaddis java_chapter_10_5eEo gaddis java_chapter_10_5e
Eo gaddis java_chapter_10_5eGina Bullock
 
Programming with C++
Programming with C++Programming with C++
Programming with C++ssuser802d47
 
Exception handling
Exception handlingException handling
Exception handlingMinal Maniar
 
Exception handling
Exception handlingException handling
Exception handlingRavi Sharda
 
Role of .NET in Exception Handling
Role of .NET in Exception HandlingRole of .NET in Exception Handling
Role of .NET in Exception HandlingAsrarulhaq Maktedar
 
Exception handling
Exception handlingException handling
Exception handlingpooja kumari
 
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.pptxsunilsoni446112
 
Exception handling
Exception handlingException handling
Exception handlingRaja Sekhar
 
UNIT III 2021R.pptx
UNIT III 2021R.pptxUNIT III 2021R.pptx
UNIT III 2021R.pptxRDeepa9
 
UNIT III 2021R.pptx
UNIT III 2021R.pptxUNIT III 2021R.pptx
UNIT III 2021R.pptxRDeepa9
 
Exception Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception HandlingException Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception HandlingAboMohammad10
 
Debugging java deployments_2
Debugging java deployments_2Debugging java deployments_2
Debugging java deployments_2Rohit Kelapure
 
Java căn bản - Chapter8
Java căn bản - Chapter8Java căn bản - Chapter8
Java căn bản - Chapter8Vince Vo
 
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 summaryEduardo Bergavera
 

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
 
Java căn bản - Chapter8
Java căn bản - Chapter8Java căn bản - Chapter8
Java căn bản - Chapter8
 
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
 
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_syllhccit
 
Snr ipt 10_guide
Snr ipt 10_guideSnr ipt 10_guide
Snr ipt 10_guidehccit
 
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_yr11hccit
 
10 ict photoshop_proj_2014
10 ict photoshop_proj_201410 ict photoshop_proj_2014
10 ict photoshop_proj_2014hccit
 
Photoshop
PhotoshopPhotoshop
Photoshophccit
 
Flash
FlashFlash
Flashhccit
 
Griffith sciences pathway programs overview
Griffith sciences pathway programs overviewGriffith sciences pathway programs overview
Griffith sciences pathway programs overviewhccit
 
Griffith info tech brochure
Griffith info tech brochureGriffith info tech brochure
Griffith info tech brochurehccit
 
Pm sql exercises
Pm sql exercisesPm sql exercises
Pm sql exerciseshccit
 
Repairs questions
Repairs questionsRepairs questions
Repairs questionshccit
 
Movies questions
Movies questionsMovies questions
Movies questionshccit
 
Australian birds questions
Australian birds questionsAustralian birds questions
Australian birds questionshccit
 
Section b
Section bSection b
Section bhccit
 
Section a
Section aSection a
Section ahccit
 
Ask manual rev5
Ask manual rev5Ask manual rev5
Ask manual rev5hccit
 
Case study report mj
Case study report mjCase study report mj
Case study report mjhccit
 
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_completedqhccit
 
Case study plan mj
Case study plan mjCase study plan mj
Case study plan mjhccit
 

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

Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfOverkill Security
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024The Digital Insurer
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsNanddeep Nachan
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
A Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusA Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusZilliz
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024The Digital Insurer
 
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelNavi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelDeepika Singh
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Jeffrey Haguewood
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 

Recently uploaded (20)

Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
A Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusA Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source Milvus
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelNavi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 

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