SlideShare une entreprise Scribd logo
1  sur  3
1
cs205: engineering software
university of virginia fall 2006
Programming
Exceptionally
David Evans
www.cs.virginia.edu/cs205 2cs205: engineering software
Quiz Answers
2. What is an object?
– Java-specific answers:
• What you get when you invoke a class
constructor
• An instance of a class
– General answers
• An entity that includes both state and
procedures for manipulating that state
– Really general answers
• “Something intelligible or perceptible by the
mind.” (Philosophy dictionary answer)
3cs205: engineering software
Mystery Method
public void f (String s) {
char c = s.charAt (0);
if (c == ‘-’) {
s.concat (“negative”);
}
}
4cs205: engineering software
public void f (String s) {
char c = s.charAt (0);
if (c == ‘-’) {
s.concat (“negative”);
}
}
public char charAt(int index)
// REQUIRES: The value of index is
// between 0 and the length of this - 1.
// EFFECTS: ...
public String concat(String s)
// EFFECTS: Returns a new string that is
// the concatenation of this followed by s.
5cs205: engineering software
Mode Specification
public int mode (int [] a)
// MODIFIES: a
// EFFECTS: Returns the value that
// appears most often in a.
6cs205: engineering software
Mode Specification
public int mode (int [] a)
// MODIFIES: a
// EFFECTS: Returns the value that
// appears most often in a.
If something is listed in MODIFIES,
how it can change must be described in
EFFECTS. Recall that MODIFIES means
everything not listed is unchanged.
2
7cs205: engineering software
Mode Specification
public int mode (int [] a)
// REQUIRES: a has at least one element
// EFFECTS: Returns the value that
// appears most often in a.
Note this is misleading.
There may be multiple
values.
8cs205: engineering software
Implementing Mode
static public int mode (int[] a) {
int best = a[0];
int bestcount = 1;
for (int i = 0; i < a.length; i++) {
int val = a[i];
int count = 0;
for (int j = 0; j < a.length; j++) {
if (a[j] == val) { count++; } }
if (count > bestcount) {
best = val; bestcount = count;
} }
return best; }
Note: I am
using poor
code
formatting to
fit on one
slide. Your
code should
not look like
this! (Hint:
use Ctrl-Shift-F
in Eclipse)
9cs205: engineering software
Violating Requires
• In C/C++: can lead to anything
– Machine crash
– Security compromise
– Strange results
• In Java: often leads to runtime
exception
10cs205: engineering software
Exception in thread "main"
java.lang.ArrayIndexOutOfBoundsException: 0
at Quiz.mode(Quiz.java:3)
at Quiz.main(Quiz.java:27)
static public int mode (int[] a) {
int best = a[0];
int bestcount = 1;
for (int i = 0; i < a.length; i++) {
int val = a[i];
int count = 0;
for (int j = 0; j < a.length; j++) {
if (a[j] == val) { count++; } }
if (count > bestcount) {
best = val; bestcount = count;
} }
return best; }
11cs205: engineering software
Use Exceptions to Remove Requires
static public int mode (int [] a)
// REQUIRES: a has at least one element
// EFFECTS: Returns the value that
// appears most often in a.
static public int mode (int [] a)
throws NoModeException
// EFFECTS: If a is empty throws NoModeException.
// Otherwise, returns the value that appears most
// often in a.
12cs205: engineering software
Throwing Exceptions
static public int mode (int [] a) throws NoModeException
{
if (a == null || size () == 0)
throw new NoModeException ();
...
}
What is NoModeException?
3
13cs205: engineering software
Exceptions are Objects
public class NoModeException
extends Exception
{
public NoModeException () {
super ();
}
}
extends Exception means
EmptyException inherits from the
Exception type (in the Java API).
Exception
NoModeException
We will cover subtyping and
inheritance later.
14cs205: engineering software
Compiler Checking
static public void main(String[] args) {
int[] tarray1 = { 1, 2, 2, 3, 2, 5 };
int[] tarray2 = {};
System.out.println("Mode tarray1: " + mode(tarray1));
System.out.println("Mode tarray2: " + mode(tarray2));
}
Unhandled exception type NoModeException
15cs205: engineering software
Catching Exceptions
static public void main(String[] args) {
int[] tarray1 = { 1, 2, 2, 3, 2, 5 };
int[] tarray2 = {};
try {
System.out.println("Mode tarray1: " + mode(tarray1));
} catch (NoModeException nme) {
System.err.println("Error: " + nme);
}
try {
System.out.println("Mode tarray2: " + mode(tarray2));
} catch (NoModeException nme) {
System.err.println("Error: " + nme);
}
}
Code inside the try block executes normally
until it throws an exception. If no exception
is thrown, execution proceeds after the
catch. If the NoModeException exception is
thrown, the catch handler runs.
16cs205: engineering software
Charge
• PS2 is due Friday
• Next class:
– Lots more issues with Exceptions
– Data abstraction

Contenu connexe

Tendances

Aftermath of functional programming. the good parts
Aftermath of functional programming. the good partsAftermath of functional programming. the good parts
Aftermath of functional programming. the good partsGuillermo Gutiérrez
 
Test final jav_aaa
Test final jav_aaaTest final jav_aaa
Test final jav_aaaBagusBudi11
 
Automated Program Repair Keynote talk
Automated Program Repair Keynote talkAutomated Program Repair Keynote talk
Automated Program Repair Keynote talkAbhik Roychoudhury
 
Exception Handling in the C++ Constructor
Exception Handling in the C++ ConstructorException Handling in the C++ Constructor
Exception Handling in the C++ ConstructorSomenath Mukhopadhyay
 
How to Profit from Static Analysis
How to Profit from Static AnalysisHow to Profit from Static Analysis
How to Profit from Static AnalysisElena Laskavaia
 
Bridging Proprietary Modelling and Open-Source Model Management Tools: The Ca...
Bridging Proprietary Modelling and Open-Source Model Management Tools: The Ca...Bridging Proprietary Modelling and Open-Source Model Management Tools: The Ca...
Bridging Proprietary Modelling and Open-Source Model Management Tools: The Ca...Thanos Zolotas
 
12. Java Exceptions and error handling
12. Java Exceptions and error handling12. Java Exceptions and error handling
12. Java Exceptions and error handlingIntro C# Book
 
DLint: dynamically checking bad coding practices in JavaScript (ISSTA'15 Slides)
DLint: dynamically checking bad coding practices in JavaScript (ISSTA'15 Slides)DLint: dynamically checking bad coding practices in JavaScript (ISSTA'15 Slides)
DLint: dynamically checking bad coding practices in JavaScript (ISSTA'15 Slides)Liang Gong
 
From Elixir to Akka (and back) - ElixirConf Mx 2017
From Elixir to Akka (and back) - ElixirConf Mx 2017From Elixir to Akka (and back) - ElixirConf Mx 2017
From Elixir to Akka (and back) - ElixirConf Mx 2017Agustin Ramos
 

Tendances (15)

Aftermath of functional programming. the good parts
Aftermath of functional programming. the good partsAftermath of functional programming. the good parts
Aftermath of functional programming. the good parts
 
Symbexecsearch
SymbexecsearchSymbexecsearch
Symbexecsearch
 
5 raii
5 raii5 raii
5 raii
 
Test final jav_aaa
Test final jav_aaaTest final jav_aaa
Test final jav_aaa
 
Mutation @ Spotify
Mutation @ Spotify Mutation @ Spotify
Mutation @ Spotify
 
Abhik-Satish-dagstuhl
Abhik-Satish-dagstuhlAbhik-Satish-dagstuhl
Abhik-Satish-dagstuhl
 
Automated Program Repair Keynote talk
Automated Program Repair Keynote talkAutomated Program Repair Keynote talk
Automated Program Repair Keynote talk
 
Exception Handling in the C++ Constructor
Exception Handling in the C++ ConstructorException Handling in the C++ Constructor
Exception Handling in the C++ Constructor
 
How to Profit from Static Analysis
How to Profit from Static AnalysisHow to Profit from Static Analysis
How to Profit from Static Analysis
 
Bridging Proprietary Modelling and Open-Source Model Management Tools: The Ca...
Bridging Proprietary Modelling and Open-Source Model Management Tools: The Ca...Bridging Proprietary Modelling and Open-Source Model Management Tools: The Ca...
Bridging Proprietary Modelling and Open-Source Model Management Tools: The Ca...
 
12. Java Exceptions and error handling
12. Java Exceptions and error handling12. Java Exceptions and error handling
12. Java Exceptions and error handling
 
DLint: dynamically checking bad coding practices in JavaScript (ISSTA'15 Slides)
DLint: dynamically checking bad coding practices in JavaScript (ISSTA'15 Slides)DLint: dynamically checking bad coding practices in JavaScript (ISSTA'15 Slides)
DLint: dynamically checking bad coding practices in JavaScript (ISSTA'15 Slides)
 
Unit iii
Unit iiiUnit iii
Unit iii
 
From Elixir to Akka (and back) - ElixirConf Mx 2017
From Elixir to Akka (and back) - ElixirConf Mx 2017From Elixir to Akka (and back) - ElixirConf Mx 2017
From Elixir to Akka (and back) - ElixirConf Mx 2017
 
Podem_Report
Podem_ReportPodem_Report
Podem_Report
 

En vedette (8)

Lecture5 2
Lecture5 2Lecture5 2
Lecture5 2
 
Tcp
TcpTcp
Tcp
 
1
11
1
 
Rd
RdRd
Rd
 
Lecture7
Lecture7Lecture7
Lecture7
 
Sockets
SocketsSockets
Sockets
 
Amcat+syllabus+and+sample+papers
Amcat+syllabus+and+sample+papersAmcat+syllabus+and+sample+papers
Amcat+syllabus+and+sample+papers
 
Amcat placement questions
Amcat placement questionsAmcat placement questions
Amcat placement questions
 

Similaire à Lecture6

"Quantum" performance effects
"Quantum" performance effects"Quantum" performance effects
"Quantum" performance effectsSergey Kuksenko
 
Improving Java performance at JBCNConf 2015
Improving Java performance at JBCNConf 2015Improving Java performance at JBCNConf 2015
Improving Java performance at JBCNConf 2015Raimon Ràfols
 
How to write clean & testable code without losing your mind
How to write clean & testable code without losing your mindHow to write clean & testable code without losing your mind
How to write clean & testable code without losing your mindAndreas Czakaj
 
C# Tutorial MSM_Murach chapter-15-slides
C# Tutorial MSM_Murach chapter-15-slidesC# Tutorial MSM_Murach chapter-15-slides
C# Tutorial MSM_Murach chapter-15-slidesSami Mut
 
The things we don't see – stories of Software, Scala and Akka
The things we don't see – stories of Software, Scala and AkkaThe things we don't see – stories of Software, Scala and Akka
The things we don't see – stories of Software, Scala and AkkaKonrad Malawski
 
Do I need tests when I have the compiler - Andrzej Jóźwiak - TomTom Dev Day 2020
Do I need tests when I have the compiler - Andrzej Jóźwiak - TomTom Dev Day 2020Do I need tests when I have the compiler - Andrzej Jóźwiak - TomTom Dev Day 2020
Do I need tests when I have the compiler - Andrzej Jóźwiak - TomTom Dev Day 2020Andrzej Jóźwiak
 
Getting start Java EE Action-Based MVC with Thymeleaf
Getting start Java EE Action-Based MVC with ThymeleafGetting start Java EE Action-Based MVC with Thymeleaf
Getting start Java EE Action-Based MVC with ThymeleafMasatoshi Tada
 
Improving Android Performance at Droidcon UK 2014
Improving Android Performance at Droidcon UK 2014Improving Android Performance at Droidcon UK 2014
Improving Android Performance at Droidcon UK 2014Raimon Ràfols
 
Design Patterns - Compiler Case Study - Hands-on Examples
Design Patterns - Compiler Case Study - Hands-on ExamplesDesign Patterns - Compiler Case Study - Hands-on Examples
Design Patterns - Compiler Case Study - Hands-on ExamplesGanesh Samarthyam
 
The First C# Project Analyzed
The First C# Project AnalyzedThe First C# Project Analyzed
The First C# Project AnalyzedPVS-Studio
 
SoCal Code Camp 2015: An introduction to Java 8
SoCal Code Camp 2015: An introduction to Java 8SoCal Code Camp 2015: An introduction to Java 8
SoCal Code Camp 2015: An introduction to Java 8Chaitanya Ganoo
 
Errors detected in the Visual C++ 2012 libraries
Errors detected in the Visual C++ 2012 librariesErrors detected in the Visual C++ 2012 libraries
Errors detected in the Visual C++ 2012 librariesPVS-Studio
 
Navigating the xDD Alphabet Soup
Navigating the xDD Alphabet SoupNavigating the xDD Alphabet Soup
Navigating the xDD Alphabet SoupDror Helper
 

Similaire à Lecture6 (20)

"Quantum" performance effects
"Quantum" performance effects"Quantum" performance effects
"Quantum" performance effects
 
Improving Java performance at JBCNConf 2015
Improving Java performance at JBCNConf 2015Improving Java performance at JBCNConf 2015
Improving Java performance at JBCNConf 2015
 
How to write clean & testable code without losing your mind
How to write clean & testable code without losing your mindHow to write clean & testable code without losing your mind
How to write clean & testable code without losing your mind
 
Error handling
Error handlingError handling
Error handling
 
Testability for Developers
Testability for DevelopersTestability for Developers
Testability for Developers
 
C# Tutorial MSM_Murach chapter-15-slides
C# Tutorial MSM_Murach chapter-15-slidesC# Tutorial MSM_Murach chapter-15-slides
C# Tutorial MSM_Murach chapter-15-slides
 
The things we don't see – stories of Software, Scala and Akka
The things we don't see – stories of Software, Scala and AkkaThe things we don't see – stories of Software, Scala and Akka
The things we don't see – stories of Software, Scala and Akka
 
Do I need tests when I have the compiler - Andrzej Jóźwiak - TomTom Dev Day 2020
Do I need tests when I have the compiler - Andrzej Jóźwiak - TomTom Dev Day 2020Do I need tests when I have the compiler - Andrzej Jóźwiak - TomTom Dev Day 2020
Do I need tests when I have the compiler - Andrzej Jóźwiak - TomTom Dev Day 2020
 
Getting start Java EE Action-Based MVC with Thymeleaf
Getting start Java EE Action-Based MVC with ThymeleafGetting start Java EE Action-Based MVC with Thymeleaf
Getting start Java EE Action-Based MVC with Thymeleaf
 
Improving Android Performance at Droidcon UK 2014
Improving Android Performance at Droidcon UK 2014Improving Android Performance at Droidcon UK 2014
Improving Android Performance at Droidcon UK 2014
 
Design Patterns - Compiler Case Study - Hands-on Examples
Design Patterns - Compiler Case Study - Hands-on ExamplesDesign Patterns - Compiler Case Study - Hands-on Examples
Design Patterns - Compiler Case Study - Hands-on Examples
 
The First C# Project Analyzed
The First C# Project AnalyzedThe First C# Project Analyzed
The First C# Project Analyzed
 
Need 4 Speed FI
Need 4 Speed FINeed 4 Speed FI
Need 4 Speed FI
 
SoCal Code Camp 2015: An introduction to Java 8
SoCal Code Camp 2015: An introduction to Java 8SoCal Code Camp 2015: An introduction to Java 8
SoCal Code Camp 2015: An introduction to Java 8
 
Errors detected in the Visual C++ 2012 libraries
Errors detected in the Visual C++ 2012 librariesErrors detected in the Visual C++ 2012 libraries
Errors detected in the Visual C++ 2012 libraries
 
L04 Software Design Examples
L04 Software Design ExamplesL04 Software Design Examples
L04 Software Design Examples
 
SCALA - Functional domain
SCALA -  Functional domainSCALA -  Functional domain
SCALA - Functional domain
 
00_Introduction to Java.ppt
00_Introduction to Java.ppt00_Introduction to Java.ppt
00_Introduction to Java.ppt
 
Navigating the xDD Alphabet Soup
Navigating the xDD Alphabet SoupNavigating the xDD Alphabet Soup
Navigating the xDD Alphabet Soup
 
Unit testing - A&BP CC
Unit testing - A&BP CCUnit testing - A&BP CC
Unit testing - A&BP CC
 

Dernier

Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
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
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusZilliz
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
 
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
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
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
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...apidays
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024The Digital Insurer
 
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
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
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
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfOrbitshub
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistandanishmna97
 

Dernier (20)

Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
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
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
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
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
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
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
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
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 

Lecture6

  • 1. 1 cs205: engineering software university of virginia fall 2006 Programming Exceptionally David Evans www.cs.virginia.edu/cs205 2cs205: engineering software Quiz Answers 2. What is an object? – Java-specific answers: • What you get when you invoke a class constructor • An instance of a class – General answers • An entity that includes both state and procedures for manipulating that state – Really general answers • “Something intelligible or perceptible by the mind.” (Philosophy dictionary answer) 3cs205: engineering software Mystery Method public void f (String s) { char c = s.charAt (0); if (c == ‘-’) { s.concat (“negative”); } } 4cs205: engineering software public void f (String s) { char c = s.charAt (0); if (c == ‘-’) { s.concat (“negative”); } } public char charAt(int index) // REQUIRES: The value of index is // between 0 and the length of this - 1. // EFFECTS: ... public String concat(String s) // EFFECTS: Returns a new string that is // the concatenation of this followed by s. 5cs205: engineering software Mode Specification public int mode (int [] a) // MODIFIES: a // EFFECTS: Returns the value that // appears most often in a. 6cs205: engineering software Mode Specification public int mode (int [] a) // MODIFIES: a // EFFECTS: Returns the value that // appears most often in a. If something is listed in MODIFIES, how it can change must be described in EFFECTS. Recall that MODIFIES means everything not listed is unchanged.
  • 2. 2 7cs205: engineering software Mode Specification public int mode (int [] a) // REQUIRES: a has at least one element // EFFECTS: Returns the value that // appears most often in a. Note this is misleading. There may be multiple values. 8cs205: engineering software Implementing Mode static public int mode (int[] a) { int best = a[0]; int bestcount = 1; for (int i = 0; i < a.length; i++) { int val = a[i]; int count = 0; for (int j = 0; j < a.length; j++) { if (a[j] == val) { count++; } } if (count > bestcount) { best = val; bestcount = count; } } return best; } Note: I am using poor code formatting to fit on one slide. Your code should not look like this! (Hint: use Ctrl-Shift-F in Eclipse) 9cs205: engineering software Violating Requires • In C/C++: can lead to anything – Machine crash – Security compromise – Strange results • In Java: often leads to runtime exception 10cs205: engineering software Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0 at Quiz.mode(Quiz.java:3) at Quiz.main(Quiz.java:27) static public int mode (int[] a) { int best = a[0]; int bestcount = 1; for (int i = 0; i < a.length; i++) { int val = a[i]; int count = 0; for (int j = 0; j < a.length; j++) { if (a[j] == val) { count++; } } if (count > bestcount) { best = val; bestcount = count; } } return best; } 11cs205: engineering software Use Exceptions to Remove Requires static public int mode (int [] a) // REQUIRES: a has at least one element // EFFECTS: Returns the value that // appears most often in a. static public int mode (int [] a) throws NoModeException // EFFECTS: If a is empty throws NoModeException. // Otherwise, returns the value that appears most // often in a. 12cs205: engineering software Throwing Exceptions static public int mode (int [] a) throws NoModeException { if (a == null || size () == 0) throw new NoModeException (); ... } What is NoModeException?
  • 3. 3 13cs205: engineering software Exceptions are Objects public class NoModeException extends Exception { public NoModeException () { super (); } } extends Exception means EmptyException inherits from the Exception type (in the Java API). Exception NoModeException We will cover subtyping and inheritance later. 14cs205: engineering software Compiler Checking static public void main(String[] args) { int[] tarray1 = { 1, 2, 2, 3, 2, 5 }; int[] tarray2 = {}; System.out.println("Mode tarray1: " + mode(tarray1)); System.out.println("Mode tarray2: " + mode(tarray2)); } Unhandled exception type NoModeException 15cs205: engineering software Catching Exceptions static public void main(String[] args) { int[] tarray1 = { 1, 2, 2, 3, 2, 5 }; int[] tarray2 = {}; try { System.out.println("Mode tarray1: " + mode(tarray1)); } catch (NoModeException nme) { System.err.println("Error: " + nme); } try { System.out.println("Mode tarray2: " + mode(tarray2)); } catch (NoModeException nme) { System.err.println("Error: " + nme); } } Code inside the try block executes normally until it throws an exception. If no exception is thrown, execution proceeds after the catch. If the NoModeException exception is thrown, the catch handler runs. 16cs205: engineering software Charge • PS2 is due Friday • Next class: – Lots more issues with Exceptions – Data abstraction