SlideShare una empresa de Scribd logo
1 de 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

Más contenido relacionado

La actualidad más candente

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
 

La actualidad más candente (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
 

Destacado (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
 

Similar a 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
 

Similar a 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
 

Último

JavaScript Usage Statistics 2024 - The Ultimate Guide
JavaScript Usage Statistics 2024 - The Ultimate GuideJavaScript Usage Statistics 2024 - The Ultimate Guide
JavaScript Usage Statistics 2024 - The Ultimate GuidePixlogix Infotech
 
Vector Search @ sw2con for slideshare.pptx
Vector Search @ sw2con for slideshare.pptxVector Search @ sw2con for slideshare.pptx
Vector Search @ sw2con for slideshare.pptxjbellis
 
ADP Passwordless Journey Case Study.pptx
ADP Passwordless Journey Case Study.pptxADP Passwordless Journey Case Study.pptx
ADP Passwordless Journey Case Study.pptxFIDO Alliance
 
The Value of Certifying Products for FDO _ Paul at FIDO Alliance.pdf
The Value of Certifying Products for FDO _ Paul at FIDO Alliance.pdfThe Value of Certifying Products for FDO _ Paul at FIDO Alliance.pdf
The Value of Certifying Products for FDO _ Paul at FIDO Alliance.pdfFIDO Alliance
 
How Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdf
How Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdfHow Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdf
How Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdfFIDO Alliance
 
2024 May Patch Tuesday
2024 May Patch Tuesday2024 May Patch Tuesday
2024 May Patch TuesdayIvanti
 
Event-Driven Architecture Masterclass: Challenges in Stream Processing
Event-Driven Architecture Masterclass: Challenges in Stream ProcessingEvent-Driven Architecture Masterclass: Challenges in Stream Processing
Event-Driven Architecture Masterclass: Challenges in Stream ProcessingScyllaDB
 
Event-Driven Architecture Masterclass: Engineering a Robust, High-performance...
Event-Driven Architecture Masterclass: Engineering a Robust, High-performance...Event-Driven Architecture Masterclass: Engineering a Robust, High-performance...
Event-Driven Architecture Masterclass: Engineering a Robust, High-performance...ScyllaDB
 
Design and Development of a Provenance Capture Platform for Data Science
Design and Development of a Provenance Capture Platform for Data ScienceDesign and Development of a Provenance Capture Platform for Data Science
Design and Development of a Provenance Capture Platform for Data SciencePaolo Missier
 
How we scaled to 80K users by doing nothing!.pdf
How we scaled to 80K users by doing nothing!.pdfHow we scaled to 80K users by doing nothing!.pdf
How we scaled to 80K users by doing nothing!.pdfSrushith Repakula
 
Harnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptx
Harnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptxHarnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptx
Harnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptxFIDO Alliance
 
Top 10 CodeIgniter Development Companies
Top 10 CodeIgniter Development CompaniesTop 10 CodeIgniter Development Companies
Top 10 CodeIgniter Development CompaniesTopCSSGallery
 
Generative AI Use Cases and Applications.pdf
Generative AI Use Cases and Applications.pdfGenerative AI Use Cases and Applications.pdf
Generative AI Use Cases and Applications.pdfalexjohnson7307
 
State of the Smart Building Startup Landscape 2024!
State of the Smart Building Startup Landscape 2024!State of the Smart Building Startup Landscape 2024!
State of the Smart Building Startup Landscape 2024!Memoori
 
Introduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdf
Introduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdfIntroduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdf
Introduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdfFIDO Alliance
 
Observability Concepts EVERY Developer Should Know (DevOpsDays Seattle)
Observability Concepts EVERY Developer Should Know (DevOpsDays Seattle)Observability Concepts EVERY Developer Should Know (DevOpsDays Seattle)
Observability Concepts EVERY Developer Should Know (DevOpsDays Seattle)Paige Cruz
 
Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...
Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...
Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...panagenda
 
WebRTC and SIP not just audio and video @ OpenSIPS 2024
WebRTC and SIP not just audio and video @ OpenSIPS 2024WebRTC and SIP not just audio and video @ OpenSIPS 2024
WebRTC and SIP not just audio and video @ OpenSIPS 2024Lorenzo Miniero
 
WebAssembly is Key to Better LLM Performance
WebAssembly is Key to Better LLM PerformanceWebAssembly is Key to Better LLM Performance
WebAssembly is Key to Better LLM PerformanceSamy Fodil
 
ASRock Industrial FDO Solutions in Action for Industrial Edge AI _ Kenny at A...
ASRock Industrial FDO Solutions in Action for Industrial Edge AI _ Kenny at A...ASRock Industrial FDO Solutions in Action for Industrial Edge AI _ Kenny at A...
ASRock Industrial FDO Solutions in Action for Industrial Edge AI _ Kenny at A...FIDO Alliance
 

Último (20)

JavaScript Usage Statistics 2024 - The Ultimate Guide
JavaScript Usage Statistics 2024 - The Ultimate GuideJavaScript Usage Statistics 2024 - The Ultimate Guide
JavaScript Usage Statistics 2024 - The Ultimate Guide
 
Vector Search @ sw2con for slideshare.pptx
Vector Search @ sw2con for slideshare.pptxVector Search @ sw2con for slideshare.pptx
Vector Search @ sw2con for slideshare.pptx
 
ADP Passwordless Journey Case Study.pptx
ADP Passwordless Journey Case Study.pptxADP Passwordless Journey Case Study.pptx
ADP Passwordless Journey Case Study.pptx
 
The Value of Certifying Products for FDO _ Paul at FIDO Alliance.pdf
The Value of Certifying Products for FDO _ Paul at FIDO Alliance.pdfThe Value of Certifying Products for FDO _ Paul at FIDO Alliance.pdf
The Value of Certifying Products for FDO _ Paul at FIDO Alliance.pdf
 
How Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdf
How Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdfHow Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdf
How Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdf
 
2024 May Patch Tuesday
2024 May Patch Tuesday2024 May Patch Tuesday
2024 May Patch Tuesday
 
Event-Driven Architecture Masterclass: Challenges in Stream Processing
Event-Driven Architecture Masterclass: Challenges in Stream ProcessingEvent-Driven Architecture Masterclass: Challenges in Stream Processing
Event-Driven Architecture Masterclass: Challenges in Stream Processing
 
Event-Driven Architecture Masterclass: Engineering a Robust, High-performance...
Event-Driven Architecture Masterclass: Engineering a Robust, High-performance...Event-Driven Architecture Masterclass: Engineering a Robust, High-performance...
Event-Driven Architecture Masterclass: Engineering a Robust, High-performance...
 
Design and Development of a Provenance Capture Platform for Data Science
Design and Development of a Provenance Capture Platform for Data ScienceDesign and Development of a Provenance Capture Platform for Data Science
Design and Development of a Provenance Capture Platform for Data Science
 
How we scaled to 80K users by doing nothing!.pdf
How we scaled to 80K users by doing nothing!.pdfHow we scaled to 80K users by doing nothing!.pdf
How we scaled to 80K users by doing nothing!.pdf
 
Harnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptx
Harnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptxHarnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptx
Harnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptx
 
Top 10 CodeIgniter Development Companies
Top 10 CodeIgniter Development CompaniesTop 10 CodeIgniter Development Companies
Top 10 CodeIgniter Development Companies
 
Generative AI Use Cases and Applications.pdf
Generative AI Use Cases and Applications.pdfGenerative AI Use Cases and Applications.pdf
Generative AI Use Cases and Applications.pdf
 
State of the Smart Building Startup Landscape 2024!
State of the Smart Building Startup Landscape 2024!State of the Smart Building Startup Landscape 2024!
State of the Smart Building Startup Landscape 2024!
 
Introduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdf
Introduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdfIntroduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdf
Introduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdf
 
Observability Concepts EVERY Developer Should Know (DevOpsDays Seattle)
Observability Concepts EVERY Developer Should Know (DevOpsDays Seattle)Observability Concepts EVERY Developer Should Know (DevOpsDays Seattle)
Observability Concepts EVERY Developer Should Know (DevOpsDays Seattle)
 
Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...
Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...
Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...
 
WebRTC and SIP not just audio and video @ OpenSIPS 2024
WebRTC and SIP not just audio and video @ OpenSIPS 2024WebRTC and SIP not just audio and video @ OpenSIPS 2024
WebRTC and SIP not just audio and video @ OpenSIPS 2024
 
WebAssembly is Key to Better LLM Performance
WebAssembly is Key to Better LLM PerformanceWebAssembly is Key to Better LLM Performance
WebAssembly is Key to Better LLM Performance
 
ASRock Industrial FDO Solutions in Action for Industrial Edge AI _ Kenny at A...
ASRock Industrial FDO Solutions in Action for Industrial Edge AI _ Kenny at A...ASRock Industrial FDO Solutions in Action for Industrial Edge AI _ Kenny at A...
ASRock Industrial FDO Solutions in Action for Industrial Edge AI _ Kenny at A...
 

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