SlideShare ist ein Scribd-Unternehmen logo
1 von 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

Weitere ähnliche Inhalte

Was ist angesagt?

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
 

Was ist angesagt? (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
 

Andere mochten auch (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
 

Ähnlich wie 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
 

Ähnlich wie 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
 

Kürzlich hochgeladen

Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...gurkirankumar98700
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
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
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 

Kürzlich hochgeladen (20)

Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
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
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 

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