Loading...

Messages

Proposals

Stuck in your homework and missing deadline? Get urgent help in $10/Page with 24 hours deadline

Get Urgent Writing Help In Your Essays, Assignments, Homeworks, Dissertation, Thesis Or Coursework & Achieve A+ Grades.

Privacy Guaranteed - 100% Plagiarism Free Writing - Free Turnitin Report - Professional And Experienced Writers - 24/7 Online Support

C# catch multiple exception types

24/11/2021 Client: muhammad11 Deadline: 2 Day

An Object-Oriented Approach to Programming Logic and Design Fourth Edition

Chapter 10

Exception Handling

Objectives

In this chapter, you will learn about:

Exceptions

The limitations of traditional error handling

Trying code and catching exceptions

Throwing and catching multiple exceptions

Using the finally block

The advantages of exception handling

Tracing exceptions through the call stack

Creating your own exceptions

2

An Object-Oriented Approach to Programming Logic and Design

Learning about Exceptions

Exception

Unexpected or error condition

Occurs while program is running

Unusual occurrence

Examples

Reading a nonexistent file

Writing data to a full disk

Entering invalid input data

Dividing a value by zero

Accessing an array using too-large subscript

Calculating a value that exceeds the variable type’s limit

3

An Object-Oriented Approach to Programming Logic and Design

Learning about Exceptions (cont’d)

Exception handling

Object-oriented techniques used to manage errors

Group of methods

Handles predictable errors

Unpredictable errors

Program cannot recover

Exception handling not used

Example: power failure

4

An Object-Oriented Approach to Programming Logic and Design

5

An Object-Oriented Approach to Programming Logic and Design

Figure 10-1 illustrates a method that might divide by 0

Figure 10-2 demonstrates an exception message generated in Java when the program attempts to divide by 0

Figure 10-1

Figure 10-2

Learning about Exceptions (cont’d)

Throwing an exception

When method detects an exception

Failure to handle exception

Program terminates: abrupt and unforgiving

Example in Figure 10-2 on previous slide

Two approaches to handling exceptions

Traditional manner

Object-oriented manner provides more elegant (and safer) solutions

6

An Object-Oriented Approach to Programming Logic and Design

Learning about Exceptions (cont’d)

Examples of typical exceptions

Attempt to divide by zero

ArithmeticException or DivideByZeroException

Attempt to store object of wrong data type in an array

ArrayTypeMismatchException

Attempt to access array with invalid subscript

IndexOutOfRangeException

Object reference does not correctly refer to created object

NullReferenceException

Arithmetic operation produces a greater value than assigned memory location can accommodate

OverflowException

7

An Object-Oriented Approach to Programming Logic and Design

Understanding the Limitations of Traditional Error Handling

Error conditions existed before object-oriented methods

Most common error-handling solution

Make a decision before using a potentially error-causing value

Example: Figure 10-3 displays error message if divisor is zero

8

An Object-Oriented Approach to Programming Logic and Design

Figure 10-3

Understanding the Limitations of Traditional Error Handling (cont’d)

Alternative solutions and issues

Prompt user for new value

Not useful if application retrieves file input

Force divisor to one

Not useful if produces wrong answer

Drawbacks to traditional error-handling approaches

Client using traditional error-handling method must accept method’s error-handling solution

Inflexible

May require multiple method versions

9

An Object-Oriented Approach to Programming Logic and Design

Understanding the Limitations of Traditional Error Handling (cont’d)

Exception handling

More elegant solution for error-handling conditions

Method detects errors, but client handles them

Terminology

“Try” code: tests a procedure that might cause an error

“Throws an exception”: the code that detects an error sends an exception object to another method or to the operating system

“Catches the exception”: a block of code receives the error and takes appropriate action

10

An Object-Oriented Approach to Programming Logic and Design

Trying Code and Catching Exceptions

try block

Block of code you attempt to execute

Can contain any number of statements or method calls

If exception occurs, the remaining statements in try block do not execute

catch block

Code segment handling exception thrown by try block

Need at least one following a try block

11

An Object-Oriented Approach to Programming Logic and Design

Trying Code and Catching Exceptions (cont’d)

throw statement

Sends an exception object out of method to be handled elsewhere

catch block

Consists of keyword catch, followed by parentheses that contain exception type and identifier

Statements that take action to handle error

An endcatch statement (pseudocode)

Can handle one exception type only

Does not execute if no exception occurs

12

An Object-Oriented Approach to Programming Logic and Design

13

An Object-Oriented Approach to Programming Logic and Design

General format of a method that includes a shaded try…catch pair

Figure 10-4

Trying Code and Catching Exceptions (cont’d)

Statements after catch block

Execute normally whether or not there is an exception

14

An Object-Oriented Approach to Programming Logic and Design

Method with a try block that attempts division

Figure 10-5

Trying Code and Catching Exceptions (cont’d)

Figure 10-5 (previous slide)

throw operation occurred implicitly

Programmer did not have to write a throw statement

throw and catch operations reside in same method

Similar to if...else pair that handles error

throw and catch blocks may reside in separate methods

Variable mistake in catch block

Object of type Exception (not used)

Exception class may contain a method called getMessage() that returns information about the cause of the error

15

An Object-Oriented Approach to Programming Logic and Design

Throwing and Catching Multiple Exceptions

try block can contain as many statements as needed

First error-generating statement throws an exception

Logic transfers to catch block

Remaining try block statements unexecuted

Can catch as many exceptions as desired

Examined sequentially until match found

Matching catch block executes

Remaining catch blocks bypassed

16

An Object-Oriented Approach to Programming Logic and Design

Figure 10-6

17

An Object-Oriented Approach to Programming Logic and Design

Program throws two types of exceptions: ArithmeticExceptions and IndexOutOfBoundsExceptions

18

An Object-Oriented Approach to Programming Logic and Design

Each of the two catch blocks displays a different message

Figure 10-7

19

An Object-Oriented Approach to Programming Logic and Design

Uses a single generic catch block to catch any type of exception

Figure 10-8

Throwing and Catching Multiple Exceptions (cont’d)

Unreachable code

Statements never execute under any circumstance

Also known as dead code

To avoid unreachable code, order catch blocks correctly

More specific exception types first

More general types follow to catch remaining errors

20

An Object-Oriented Approach to Programming Logic and Design

21

An Object-Oriented Approach to Programming Logic and Design

Class that contains an unreachable catch block

Figure 10-9

Using the finally Block

Used when specific actions are needed at the end of a try…catch sequence

Always executes whether or not exception occurred

22

An Object-Oriented Approach to Programming Logic and Design

try…catch sequence that uses a finally block

Figure 10-10

Compare Figure 10-4 with Figure 10-10

23

An Object-Oriented Approach to Programming Logic and Design

Figure 10-4

Using the finally Block (cont’d)

Comparison of Figures 10-10 and 10-4

When Figure 10-4 try code works without error

Control passes to statements at end of method

When try code fails and throws an exception

Exception is caught

catch block executes

Control passes to statements at end of method

Figure 10-4 statements at end may not execute

Unplanned (uncaught) exception occurs

Statements in try or catch block cause program termination

24

An Object-Oriented Approach to Programming Logic and Design

Using the finally Block (cont’d)

Unhandled exception

Program execution stops immediately

Exception sent to operating system

Current method abandoned

Including a finally block

Assures finally statements will execute

Before method abandoned

Even if method concludes prematurely

Often used to close data files

25

An Object-Oriented Approach to Programming Logic and Design

Using the finally Block (cont’d)

26

An Object-Oriented Approach to Programming Logic and Design

Pseudocode tries reading a file and handles an exception

finally block closes the file

Figure 10-11

Using the finally Block (cont’d)

Code in finally block executes for each of the following outcomes of the try block

try ends normally with no exceptions

try throws FileException to the catch block, which executes and ends program

Another exception causes try block to be abandoned prematurely and catch block does not execute

27

An Object-Oriented Approach to Programming Logic and Design

Understanding the Advantages of Exception Handling (cont’d)

Confusing

Error-prone

Figure 10-12: pseudocode representing traditional error checking

28

An Object-Oriented Approach to Programming Logic and Design

Handling potential program errors before advent of object-oriented languages

Figure 10-12

Understanding the Advantages of Exception Handling (cont’d)

Handling potential program errors with object-oriented techniques

29

An Object-Oriented Approach to Programming Logic and Design

Code is:

Simpler

Easier to read

More flexible

Reusable

Figure 10-13: illustrates object-oriented approach

Figure 10-13

Understanding the Advantages of Exception Handling (cont’d)

Figure 10-14: Potential error in displayPrice() method: accepts argument as array subscript

Subscript could be out of bounds

Method might throw an exception

30

An Object-Oriented Approach to Programming Logic and Design

Figure 10-14

Understanding the Advantages of Exception Handling (cont’d)

Figures 10-15 and 10-16 show two ways to handle Figure 10-14 error exception

An Object-Oriented Approach to Programming Logic and Design

31

Exception displays a price of $0

Figure 10-15

Figure 10-16

Understanding the Advantages of Exception Handling (cont’d)

An Object-Oriented Approach to Programming Logic and Design

32

Exception includes an input dialog box to prompt user for a new item number until it is within range

Tracing Exceptions through the Call Stack

When one method calls another

Operating system keeps track of calling method

Program control returns to calling method once method completes

Call stack

Memory location

Computer stores list of method memory locations

Where system must return after call completed

33

An Object-Oriented Approach to Programming Logic and Design

Tracing Exceptions through the Call Stack (cont’d)

34

An Object-Oriented Approach to Programming Logic and Design

When method throws an exception

If same method does not catch it, exception thrown to next method up the call stack

Demonstrates how call stack works

Figure 10-17

Tracing Exceptions through the Call Stack (cont’d)

If no method in chain handles the exception

Given to operating system

Passing exceptions through chain of calling methods

Advantages

Can handle exceptions wherever most appropriate (includes operating system)

Can use printStackTrace(): debugging tool that displays a list of methods in the call stack to determine location of exception

Disadvantages

Difficulty locating original source of the exception (if program uses several classes)

35

An Object-Oriented Approach to Programming Logic and Design

A Case Study: Tracing the Source of an Exception

See flaw (shaded) in Figure 10-18

Subscript set to 2 instead of 1 for higher tax rate

Out of bounds error occurs if subscript used with taxRate array

36

An Object-Oriented Approach to Programming Logic and Design

Figure 10-18

A Case Study: Tracing the Source of an Exception (cont’d)

Assume Tax class is a purchased class (black box)

Figure 10-19 shows a sample Prices class

37

An Object-Oriented Approach to Programming Logic and Design

Figure 10-19

A Case Study: Tracing the Source of an Exception (cont’d)

Figure 10-20: New application (next slide)

Asks user to enter item number

Passes item to Prices.displayPrice()

Tries item entry and catches exception

Executing program using valid item number

Receive “Error!” message from catch block

To discover what caused the message, replace catch block statement with mistake.printStackTrace()

38

An Object-Oriented Approach to Programming Logic and Design

A Case Study: Tracing the Source of an Exception (cont’d)

39

An Object-Oriented Approach to Programming Logic and Design

Prompts user for an item number and passes it to Prices.displayPrice()

Figure 10-20

A Case Study: Tracing the Source of an Exception (cont’d)

40

An Object-Oriented Approach to Programming Logic and Design

Figure 10-21 shows output from C# execution

Figure 10-21

Creating Your Own Exceptions

Object-oriented languages provide built-in Exception types

Cannot predict every possible condition

Programmer may create application-specific exceptions

Usually extend a built-in Exception class

41

An Object-Oriented Approach to Programming Logic and Design

Creating Your Own Exceptions (cont’d)

42

An Object-Oriented Approach to Programming Logic and Design

Pseudocode in Figure 10-22

Creates HighBalanceException

Assumes that the parent class contains a setMessage() method

Constructor contains a single statement to set error message

Figure 10-22

Figure 10-23

Creating Your Own Exceptions (cont’d)

43

An Object-Oriented Approach to Programming Logic and Design

CustomerAccount class using HighBalanceException

If account balance exceeds limit, an instance of the class is created and thrown

Figure 10-24

Creating Your Own Exceptions (cont’d)

44

An Object-Oriented Approach to Programming Logic and Design

Application constructs a CustomerAccount object within a try block

Creating Your Own Exceptions (cont’d)

Do not create excessive number of special Exception types

Add complexity for other programmers

Advantages of specialized Exception classes

Provides elegant handling of error situations

Separates error code from normal code

Passes errors up the stack and traces them

Client classes handle exceptions in manner most suitable for the application

45

An Object-Oriented Approach to Programming Logic and Design

Summary

Exception:

Unexpected or error condition

Exception handling

Techniques used to manage actions following an exception

try block

Wraps code that might cause an exception

catch block

Set of code statements to handle specific error types

Multiple catch blocks

Handle different error types

46

An Object-Oriented Approach to Programming Logic and Design

Summary (cont’d)

finally block

Statements always executed after try block

Used to perform cleanup tasks

Object-oriented exception-handling techniques

Provide flexibility in handling exceptions

Call stack

Memory location storing method locations list

Built-in exceptions

Cannot predict every condition

Can write your own exceptions

47

An Object-Oriented Approach to Programming Logic and Design

Homework is Completed By:

Writer Writer Name Amount Client Comments & Rating
Instant Homework Helper

ONLINE

Instant Homework Helper

$36

She helped me in last minute in a very reasonable price. She is a lifesaver, I got A+ grade in my homework, I will surely hire her again for my next assignments, Thumbs Up!

Order & Get This Solution Within 3 Hours in $25/Page

Custom Original Solution And Get A+ Grades

  • 100% Plagiarism Free
  • Proper APA/MLA/Harvard Referencing
  • Delivery in 3 Hours After Placing Order
  • Free Turnitin Report
  • Unlimited Revisions
  • Privacy Guaranteed

Order & Get This Solution Within 6 Hours in $20/Page

Custom Original Solution And Get A+ Grades

  • 100% Plagiarism Free
  • Proper APA/MLA/Harvard Referencing
  • Delivery in 6 Hours After Placing Order
  • Free Turnitin Report
  • Unlimited Revisions
  • Privacy Guaranteed

Order & Get This Solution Within 12 Hours in $15/Page

Custom Original Solution And Get A+ Grades

  • 100% Plagiarism Free
  • Proper APA/MLA/Harvard Referencing
  • Delivery in 12 Hours After Placing Order
  • Free Turnitin Report
  • Unlimited Revisions
  • Privacy Guaranteed

6 writers have sent their proposals to do this homework:

Quick N Quality
WRITING LAND
Engineering Help
Top Essay Tutor
Financial Analyst
Buy Coursework Help
Writer Writer Name Offer Chat
Quick N Quality

ONLINE

Quick N Quality

I am an experienced researcher here with master education. After reading your posting, I feel, you need an expert research writer to complete your project.Thank You

$23 Chat With Writer
WRITING LAND

ONLINE

WRITING LAND

I reckon that I can perfectly carry this project for you! I am a research writer and have been writing academic papers, business reports, plans, literature review, reports and others for the past 1 decade.

$15 Chat With Writer
Engineering Help

ONLINE

Engineering Help

I will be delighted to work on your project. As an experienced writer, I can provide you top quality, well researched, concise and error-free work within your provided deadline at very reasonable prices.

$20 Chat With Writer
Top Essay Tutor

ONLINE

Top Essay Tutor

I am a professional and experienced writer and I have written research reports, proposals, essays, thesis and dissertations on a variety of topics.

$18 Chat With Writer
Financial Analyst

ONLINE

Financial Analyst

I am a professional and experienced writer and I have written research reports, proposals, essays, thesis and dissertations on a variety of topics.

$20 Chat With Writer
Buy Coursework Help

ONLINE

Buy Coursework Help

I have done dissertations, thesis, reports related to these topics, and I cover all the CHAPTERS accordingly and provide proper updates on the project.

$31 Chat With Writer

Let our expert academic writers to help you in achieving a+ grades in your homework, assignment, quiz or exam.

Similar Homework Questions

Order the five images below along the timeline based on the sequence of geologic events. - Ethical issues in group counseling - Sig roofing kentish town - Uncle tobys anzac biscuits - Bus 475 week 5 final strategic plan - Jcpenney business model - Mental health treatment plan template - Cloud Computing - Igcse global perspectives textbook pdf - Introduction to psychology by morgan and king ppt - Organic compound in a sentence - Advantages of limiting car usage essay - Assignment - Regression and Correlation Analysis - Border collie white tail tip - Ac motor speed controller india - Is spartacus a true story - English - Variable rate overtime frito lay - Neutralization capacity of commercial antacid tablet lab report - Individual and group learning - Jennifer hoffman vsim - Week 5 Report - Marketing and public relations reading quiz - Deliverable 6 - Actionable Insights and Business Problems TABLEAU Presentation and WORD Doc - What is ca gen - Dunkin donuts organizational structure - Dr heng wee soon - Gallstone flushing epsom salt - Timken torrington acquisition case - 10 facts about the dewey decimal system - How to calculate lateral earth pressure - Information server 11.7 system requirements - Influences on behavior and psychological disorders presentation - First fleet convicts database - Porphyrin is a pigment in blood protoplasm - Finance week 4 case - Fundamentals of organizational behavior 5th edition pdf - According to freud, dream images, memory lapses, inadvertent slips of the tongue, and accidents: - Lexical analyzer code in java - Mary and the angel - Marketing Suggestions - Analysing a running record - Www bbc co uk schools typing level 1 4 - Cisco rvs4000 vpn setup wizard - Network security proposal part 2 - Trinity guildhall speech and drama - Juegan ustedes al baloncesto en la universidad - National business names register australia - Dc network.gcu - Math - How to write assessment report sample - What is a personal creed - What are the key sources of trader joe's competitive advantage - 10 20 variables that may affect seed germination - Personal assessment of management skills pams - Racial Diversity in the Classroom - Tv antenna tower collapse case study - Final - What is a pre start systems and equipment check - Krispy kreme vision statement - Rl circuit lab report - Which nutrient contains the most calories per gram - Powerpoint Presentation - Chapter 3 information systems organizations and strategy - Iki biology - Ol 125 personal development plan swot analysis milestone two - Client server computing is a - The practice of clinical psychology worksheet - Little caesars business model - Clipsal safety switch reset - Cost accounting chapter 2 ppt - Tina jones health history shadow health - Cee lo dice tricks - Which of the following is not something john claimed about love in 1 john? - Strengths and weaknesses of kirkpatrick model - John hopkins ebp model article - Calculus chain rule worksheet - Security Architecture & Design - Assignment 2 - Short student council speeches - Master data services add in for excel - Tim curry married susan sarandon - Mendel conducted his most memorable experiments on - Fetac level 3 computer literacy - Moment generating function of a constant - Analysis of Ethical Crisis and Response of "Facebook and the Cambridge Analytics Data “Breach”." - Fifo and lifo costs under perpetual inventory system - Quadruple constraints in project management - Kings fund clinical leadership - How much would it cost for someone to do a discussion for me? - Wiikano orchards case - CASES CASE 35 CIRQUE DU SOLEIL* The founder of Cirque du Soleil, Guy Laliberté, after see- ing the firm’s growth prospects wane in recent years, was thinking about expanding his firm in new directions. For three decades, the firm had reinvented and revolutionized the circus. From its beginning in 1984, Cirque de Soleil had thrilled over 150 million spectators with a novel show concept that was as original as it was nontraditional: an astonishing theatrical blend of circus acts and street enter- tainment, wrapped up in spectacular costumes and fairy- land sets and staged to spellbinding music and magical lighting. Cirque du Soleil’s business triumphs mirrored its high- flying aerial stunts, and it became a case study for business school journal articles on carving out unique markets. But following a recent bleak outlook report from a consultant, a spate of poorly received shows over the last few years, and a decline in profits, executives at Cirque said they were now restructuring a - Why is grant writing underutilized in criminal justice - Cascades mental health clinic - Thirteen plays of bhasa pdf - Yarra trams lost property - Http www vitalsource com redeem - Which protozoan group consists solely of parasitic forms - I want to be australian superwog - Context of rear window