SlideShare una empresa de Scribd logo
1 de 42
Chapter 8 Exceptions and Assertions
Objectives ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Definition ,[object Object],[object Object]
Not Catching Exceptions Error message for invalid input String inputStr; int   age; inputStr = JOptionPane.showInputDialog ( null ,  "Age:" ) ; age  = Integer.parseInt ( inputStr ) ; java.lang.NumberFormatException: ten at java.lang.Integer.parseInt(Integer.java:405) at java.lang.Integer.parseInt(Integer.java:454) at Ch8Sample1.main(Ch8Sample1.java:20)
Catching an Exception inputStr = JOptionPane.showInputDialog ( null ,  "Age:" ) ; try   { age = Integer.parseInt ( inputStr ) ; }   catch   ( NumberFormatException e ){ JOptionPane.showMessageDialog( null ,  "’"  + inputStr  +  "‘ is invalid"   +  "Please enter digits only" ); } try catch
try-catch  Control Flow
Getting Information ,[object Object],[object Object],[object Object],try   { . . . }   catch   ( NumberFormatException e ){ System.out.println ( e.getMessage ()) ; System.out.println ( e.printStackTrace ()) ; }
Multiple  catch  Blocks ,[object Object],try   { . . . age = Integer.parseInt ( inputStr ) ; . . . val = cal.get(id);  //cal is a GregorianCalendar . . . }   catch   ( NumberFormatException e ){ . . .  }  catch   ( ArrayIndexOutOfBoundsException e ){ . . .  }
Multiple  catch  Control Flow
The  finally  Block ,[object Object],[object Object]
try - catch - finally  Control Flow
Propagating Exceptions ,[object Object],[object Object],public   int  getAge ( )   throws  NumberFormatException  { . . . int  age = Integer.parseInt ( inputStr ) ; . . . return  age; }
Throwing Exceptions ,[object Object],[object Object],[object Object],public   void  doWork ( int   num )   throws  Exception  { . . . if  ( num != val )  throw new  Exception ( "Invalid val" ) ; . . . }
Exception Thrower ,[object Object],[object Object],[object Object],[object Object]
Types of Exception Throwers ,[object Object],[object Object],[object Object]
Sample Call Sequence
Exception Types ,[object Object],[object Object],[object Object]
Throwable Hierarchy ,[object Object]
Checked vs. Runtime ,[object Object],[object Object],[object Object],[object Object],[object Object]
Different Handling Rules ,[object Object],[object Object],[object Object],[object Object]
Handling Checked Exceptions
Handling Runtime Exceptions
Programmer-Defined Exceptions ,[object Object],[object Object],[object Object],[object Object]
Assertions ,[object Object],[object Object],[object Object],[object Object]
Sample Use #1 public double  deposit ( double  amount ) { double  oldBalance = balance; balance += amount; assert  balance > oldBalance; } public double  withdraw ( double  amount ) { double  oldBalance = balance; balance -= amount; assert  balance < oldBalance; }
Second Form ,[object Object],[object Object],[object Object]
Sample Use #2 public double  deposit ( double  amount ) { double  oldBalance = balance; balance += amount; assert  balance > oldBalance : &quot;Serious Error – balance did not &quot;  + &quot; increase after deposit&quot; ; }
Compiling Programs with Assertions ,[object Object],[object Object],[object Object]
Running Programs with Assertions ,[object Object],[object Object],[object Object]
Different Uses of Assertions ,[object Object],[object Object],[object Object]
Problem Statement ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Overall Plan ,[object Object],[object Object],[object Object],[object Object],[object Object]
Design Document This class maintains information on individual dorm residents. Specification for this class is provided to us. Resident The standard class for displaying messages. JOptionPane The user interface class for handling input routines.  InputHandler The given predefined class that maintains a list of Resident objects. Dorm The given predefined class that simulates the opening of a door. Door The top-level control object that manages other objects in the program. This is an instantiable main class. Ch8EntranceMonitor Purpose Class
Class Relationships (main class) Door JOptionPane Resident InputFrame Ch8EntranceMonitor Dorm
Development Steps ,[object Object],[object Object],[object Object],[object Object]
Step 1 Design ,[object Object],[object Object],[object Object]
Step 1 Code ,[object Object],[object Object],[object Object],Program source file is too big to list here. From now on, we ask you to view the source files using your Java IDE.
Step 1 Test ,[object Object],[object Object],[object Object],[object Object]
Step 2 Design ,[object Object],[object Object]
Step 2 Code ,[object Object],[object Object],[object Object],[object Object]
Step 2 Test ,[object Object],[object Object],[object Object],[object Object],[object Object]
Step 3: Finalize ,[object Object],[object Object],[object Object]

Más contenido relacionado

La actualidad más candente

Java: Objects and Object References
Java: Objects and Object ReferencesJava: Objects and Object References
Java: Objects and Object ReferencesTareq Hasan
 
Built in classes in java
Built in classes in javaBuilt in classes in java
Built in classes in javaMahmoud Ali
 
Java căn bản - Chapter2
Java căn bản - Chapter2Java căn bản - Chapter2
Java căn bản - Chapter2Vince Vo
 
Java tutorial for Beginners and Entry Level
Java tutorial for Beginners and Entry LevelJava tutorial for Beginners and Entry Level
Java tutorial for Beginners and Entry LevelRamrao Desai
 
C0 review core java1
C0 review core java1C0 review core java1
C0 review core java1tam53pm1
 
Java căn bản - Chapter7
Java căn bản - Chapter7Java căn bản - Chapter7
Java căn bản - Chapter7Vince Vo
 
C++ Object oriented concepts & programming
C++ Object oriented concepts & programmingC++ Object oriented concepts & programming
C++ Object oriented concepts & programmingnirajmandaliya
 
Generics and collections in Java
Generics and collections in JavaGenerics and collections in Java
Generics and collections in JavaGurpreet singh
 
Object and Classes in Java
Object and Classes in JavaObject and Classes in Java
Object and Classes in Javabackdoor
 
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteChapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteTushar B Kute
 
Introduction to class in java
Introduction to class in javaIntroduction to class in java
Introduction to class in javakamal kotecha
 
Object oriented programming using c++
Object oriented programming using c++Object oriented programming using c++
Object oriented programming using c++Hoang Nguyen
 
A COMPLETE FILE FOR C++
A COMPLETE FILE FOR C++A COMPLETE FILE FOR C++
A COMPLETE FILE FOR C++M Hussnain Ali
 

La actualidad más candente (20)

Java: Objects and Object References
Java: Objects and Object ReferencesJava: Objects and Object References
Java: Objects and Object References
 
Java Generics
Java GenericsJava Generics
Java Generics
 
Built in classes in java
Built in classes in javaBuilt in classes in java
Built in classes in java
 
Unit 1 Java
Unit 1 JavaUnit 1 Java
Unit 1 Java
 
Java basic
Java basicJava basic
Java basic
 
Chapter 05 classes and objects
Chapter 05 classes and objectsChapter 05 classes and objects
Chapter 05 classes and objects
 
Java căn bản - Chapter2
Java căn bản - Chapter2Java căn bản - Chapter2
Java căn bản - Chapter2
 
Java tutorial for Beginners and Entry Level
Java tutorial for Beginners and Entry LevelJava tutorial for Beginners and Entry Level
Java tutorial for Beginners and Entry Level
 
java tutorial 2
 java tutorial 2 java tutorial 2
java tutorial 2
 
C0 review core java1
C0 review core java1C0 review core java1
C0 review core java1
 
Java căn bản - Chapter7
Java căn bản - Chapter7Java căn bản - Chapter7
Java căn bản - Chapter7
 
C++ Object oriented concepts & programming
C++ Object oriented concepts & programmingC++ Object oriented concepts & programming
C++ Object oriented concepts & programming
 
Generics and collections in Java
Generics and collections in JavaGenerics and collections in Java
Generics and collections in Java
 
Object and Classes in Java
Object and Classes in JavaObject and Classes in Java
Object and Classes in Java
 
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteChapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
 
Introduction to class in java
Introduction to class in javaIntroduction to class in java
Introduction to class in java
 
M C6java2
M C6java2M C6java2
M C6java2
 
Object-Oriented Programming Using C++
Object-Oriented Programming Using C++Object-Oriented Programming Using C++
Object-Oriented Programming Using C++
 
Object oriented programming using c++
Object oriented programming using c++Object oriented programming using c++
Object oriented programming using c++
 
A COMPLETE FILE FOR C++
A COMPLETE FILE FOR C++A COMPLETE FILE FOR C++
A COMPLETE FILE FOR C++
 

Similar a Chapter 8 - Exceptions and Assertions Edit summary

Similar a Chapter 8 - Exceptions and Assertions Edit summary (20)

Md07 exceptions&assertion
Md07 exceptions&assertionMd07 exceptions&assertion
Md07 exceptions&assertion
 
Java -Exception handlingunit-iv
Java -Exception handlingunit-ivJava -Exception handlingunit-iv
Java -Exception handlingunit-iv
 
Nalinee java
Nalinee javaNalinee java
Nalinee java
 
Exception handling
Exception handlingException handling
Exception handling
 
Exception handling
Exception handlingException handling
Exception handling
 
Exceptions
ExceptionsExceptions
Exceptions
 
Java unit 11
Java unit 11Java unit 11
Java unit 11
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
 
Exceptions overview
Exceptions overviewExceptions overview
Exceptions overview
 
Java exceptions
Java exceptionsJava exceptions
Java exceptions
 
exception handling
exception handlingexception handling
exception handling
 
Exception handling
Exception handlingException handling
Exception handling
 
Exception handling in java.pptx
Exception handling in java.pptxException handling in java.pptx
Exception handling in java.pptx
 
UNIT 2.pptx
UNIT 2.pptxUNIT 2.pptx
UNIT 2.pptx
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
SUBHASH.pptx
SUBHASH.pptxSUBHASH.pptx
SUBHASH.pptx
 
Exception Handling in C#
Exception Handling in C#Exception Handling in C#
Exception Handling in C#
 
Exceptions
ExceptionsExceptions
Exceptions
 
Introduction of exception in vb.net
Introduction of exception in vb.netIntroduction of exception in vb.net
Introduction of exception in vb.net
 

Más de Eduardo Bergavera

CLP Session 5 - The Christian Family
CLP Session 5 - The Christian FamilyCLP Session 5 - The Christian Family
CLP Session 5 - The Christian FamilyEduardo Bergavera
 
Chapter 13 - Inheritance and Polymorphism
Chapter 13 - Inheritance and PolymorphismChapter 13 - Inheritance and Polymorphism
Chapter 13 - Inheritance and PolymorphismEduardo Bergavera
 
Chapter 12 - File Input and Output
Chapter 12 - File Input and OutputChapter 12 - File Input and Output
Chapter 12 - File Input and OutputEduardo Bergavera
 
Chapter 11 - Sorting and Searching
Chapter 11 - Sorting and SearchingChapter 11 - Sorting and Searching
Chapter 11 - Sorting and SearchingEduardo Bergavera
 
Chapter1 - Introduction to Object-Oriented Programming and Software Development
Chapter1 - Introduction to Object-Oriented Programming and Software DevelopmentChapter1 - Introduction to Object-Oriented Programming and Software Development
Chapter1 - Introduction to Object-Oriented Programming and Software DevelopmentEduardo Bergavera
 

Más de Eduardo Bergavera (6)

CLP Session 5 - The Christian Family
CLP Session 5 - The Christian FamilyCLP Session 5 - The Christian Family
CLP Session 5 - The Christian Family
 
What is Python?
What is Python?What is Python?
What is Python?
 
Chapter 13 - Inheritance and Polymorphism
Chapter 13 - Inheritance and PolymorphismChapter 13 - Inheritance and Polymorphism
Chapter 13 - Inheritance and Polymorphism
 
Chapter 12 - File Input and Output
Chapter 12 - File Input and OutputChapter 12 - File Input and Output
Chapter 12 - File Input and Output
 
Chapter 11 - Sorting and Searching
Chapter 11 - Sorting and SearchingChapter 11 - Sorting and Searching
Chapter 11 - Sorting and Searching
 
Chapter1 - Introduction to Object-Oriented Programming and Software Development
Chapter1 - Introduction to Object-Oriented Programming and Software DevelopmentChapter1 - Introduction to Object-Oriented Programming and Software Development
Chapter1 - Introduction to Object-Oriented Programming and Software Development
 

Último

TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demoHarshalMandlekar2
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersNicole Novielli
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
What is Artificial Intelligence?????????
What is Artificial Intelligence?????????What is Artificial Intelligence?????????
What is Artificial Intelligence?????????blackmambaettijean
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESmohitsingh558521
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsNathaniel Shimoni
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 

Último (20)

TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demo
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software Developers
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
What is Artificial Intelligence?????????
What is Artificial Intelligence?????????What is Artificial Intelligence?????????
What is Artificial Intelligence?????????
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directions
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 

Chapter 8 - Exceptions and Assertions Edit summary

  • 1. Chapter 8 Exceptions and Assertions
  • 2.
  • 3.
  • 4. Not Catching Exceptions Error message for invalid input String inputStr; int age; inputStr = JOptionPane.showInputDialog ( null , &quot;Age:&quot; ) ; age = Integer.parseInt ( inputStr ) ; java.lang.NumberFormatException: ten at java.lang.Integer.parseInt(Integer.java:405) at java.lang.Integer.parseInt(Integer.java:454) at Ch8Sample1.main(Ch8Sample1.java:20)
  • 5. Catching an Exception inputStr = JOptionPane.showInputDialog ( null , &quot;Age:&quot; ) ; try { age = Integer.parseInt ( inputStr ) ; } catch ( NumberFormatException e ){ JOptionPane.showMessageDialog( null , &quot;’&quot; + inputStr + &quot;‘ is invalid&quot; + &quot;Please enter digits only&quot; ); } try catch
  • 7.
  • 8.
  • 9. Multiple catch Control Flow
  • 10.
  • 11. try - catch - finally Control Flow
  • 12.
  • 13.
  • 14.
  • 15.
  • 17.
  • 18.
  • 19.
  • 20.
  • 23.
  • 24.
  • 25. Sample Use #1 public double deposit ( double amount ) { double oldBalance = balance; balance += amount; assert balance > oldBalance; } public double withdraw ( double amount ) { double oldBalance = balance; balance -= amount; assert balance < oldBalance; }
  • 26.
  • 27. Sample Use #2 public double deposit ( double amount ) { double oldBalance = balance; balance += amount; assert balance > oldBalance : &quot;Serious Error – balance did not &quot; + &quot; increase after deposit&quot; ; }
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33. Design Document This class maintains information on individual dorm residents. Specification for this class is provided to us. Resident The standard class for displaying messages. JOptionPane The user interface class for handling input routines. InputHandler The given predefined class that maintains a list of Resident objects. Dorm The given predefined class that simulates the opening of a door. Door The top-level control object that manages other objects in the program. This is an instantiable main class. Ch8EntranceMonitor Purpose Class
  • 34. Class Relationships (main class) Door JOptionPane Resident InputFrame Ch8EntranceMonitor Dorm
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.

Notas del editor

  1. We can increase our programs’ reliability and robustness if we catch the exceptions ourselves using error recovery routines we develop. One way to do this is to wrap the statements that may throw an exception with the try-catch control statement.
  2. Consider the given example. What would happen if the user enters a value such as the text &apos;ten&apos; instead of 10? The parseInt method cannot convert such an input to an internal numerical format. This type of error is called an exception, and it will result in displaying an error message such as the one shown here. We say the parseInt method has thrown a NumberFormatException.
  3. This example shows a way to handle a thrown exception in our code, instead of letting the system handle it, as in the previous example. If any statement inside the try block throws an exception, then the statements in the matching catch block are executed. And the program continues the execution from the statement that follows this try-catch statement.
  4. This illustrates how the control flows when there is an exception and when there is no exception. In the case when no statements in the try block throw an exception, then the catch block is skipped and execution continues with the next statement following the try-catch statement. If any one of the statements throws an exception, the statements in the catch block are executed. Execution then continues to the statement following the try-catch statement, ignoring any remaining statements in the try block.
  5. In the previous example, we simply displayed a fixed error message. We can get display a more generic error message by using the getMessage or printStrackTrace methods. We will experiment with these methods in the lab.
  6. In this example, we see two statements in the try block that can potentially throw exceptions. The parseInt method throws a NumberFormatException while the get method throws an ArrayIndexOutOfBoundsException when the argument id is outside the range of valid values.
  7. Here&apos;s how the control flows when there are multiple catch blocks. In the case when no statements in the try block throw an exception, then all catch blocks are skipped and execution continues with the next statement following the try-catch statement. If any one of the statements throws an exception, the statements in the matching catch block are executed. Execution then continues to the statement following the try-catch statement, ignoring any remaining statements in the try block.
  8. The finally block is not used often in introductory level programs, but we will introduce them here for the sake of complete coverage of the topic. For example, suppose we open a communication channel from our Java program to a remote web server to exchange data. If the data exchange is successfully completed in the try block, then we close the communication channel and finish the operation. If the data exchange is interrupted for some reason, an exception is thrown and the operation is aborted. In this case also, we need to close the communication channel, because leaving the channel open by one application blocks other applications from using it. The code to close the communication channel should therefore be placed in the finally block.
  9. Here&apos;s how the control flows when there are multiple catch blocks and the finally block. In the case when no statements in the try block throw an exception, then all catch blocks are skipped, but the statements in the finally block are executed. Execution continues with the next statement following the try-catch statement. If any one of the statements throws an exception, the statements in the matching catch block are executed first and the statements in the finally block are executed next. Execution then continues to the statement following the try-catch statement, ignoring any remaining statements in the try block.
  10. Using the try-catch statement is the first way to handle the exceptions. The second way is to propagate the thrown exception back to the caller of the method. The method that includes the statement that calls our method must either catch it or propagate it back to their caller.
  11. It is possible to throw an exception from our own method.
  12. We say a method throws an exception directly when the method includes the throw statement. Otherwise, a method is throwing an exception indirectly.
  13. This illustration shows a sequence of method calls among the exception throwers. Method D throws an instance of Exception. The green arrows indicate the direction of calls. The red arrows show the reversing of call sequence, looking for a matching catcher. Method B is the catcher. The call sequence is traced by using a stack.
  14. The classes shown here are some of the more common classes in the Throwable class hierarchy. We will be seeing most of the Exception and its subclasses shown here in the later modules.
  15. Callers of a method that can throw a checked exception must include the try-catch statement in the method body or the throws clause in the header.
  16. It is optional for callers of a method that can throw runtime exceptions to include the try-catch statement in the method body or the throws clause in the header.
  17. We will be seeing examples of using assertions in the sample programs later.
  18. For this application, we are given two helper classes. In order to use the Dorm class, we must supply the Resident class whose specification is already set so it works correctly with the given Dorm class. The relationship between the Dorm and Resident is similar to the one between the DrawingBoard and the DrawableShape classes.
  19. There will be a total of six key classes in this application. We will be designing three classes: Ch8EntranceMonitor, Resident, and InputFrame.
  20. Most relationships follow the client-service pattern, except the one between the InputFrame and Ch8EntranceMonitor follows the supervisor-subordinate pattern.
  21. Please use your Java IDE to view the source files and run the program.
  22. .