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

Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
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
 
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
 
Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGSujit Pal
 
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
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
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
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
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
 

Dernier (20)

Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
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
 
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
 
Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAG
 
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...
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
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
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 

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