Exception with arguments

Similar documents
Exceptions, Case Study-Exception handling in C++.

Exceptions Handeling

CSC 330 Object-Oriented Programming. Exception Handling CSC 330

GE U111 Engineering Problem Solving & Computation Lecture 6 February 2, 2004

21. Exceptions. Advanced Concepts: // exceptions #include <iostream> using namespace std;

CPSC 427: Object-Oriented Programming

Exceptions. Why Exception Handling?

TEMPLATES AND EXCEPTION HANDLING

C++ Programming Fundamentals

CSC 330. An Exception is. Handling Exceptions. Error Handling. Assertions. C++ Exception. Example

Review: Exam 1. Your First C++ Program. Declaration Statements. Tells the compiler. Examples of declaration statements

2. How many runtime error messages associated with exception? a) 2 b) 4 c) 5 d) infinite

Object-Oriented Programming (OOP) Fundamental Principles of OOP

C++ Crash Kurs. Exceptions. Dr. Dennis Pfisterer Institut für Telematik, Universität zu Lübeck

05-01 Discussion Notes

Exception Handling Pearson Education, Inc. All rights reserved.

Programming. C++ Basics

Data Types & Variables

Multiple Choice (Questions 1 13) 26 Points Select all correct answers (multiple correct answers are possible)

TEMPLATE IN C++ Function Templates

CS2141 Software Development using C/C++ C++ Basics

VARIABLES & ASSIGNMENTS

Introduction to Programming

Module 7 b. -Namespaces -Exceptions handling

int main() { int account = 100; // Pretend we have $100 in our account int withdrawal;

C++ PROGRAMMING LANGUAGE: DYNAMIC MEMORY ALLOCATION AND EXCEPTION IN C++. CAAM 519, CHAPTER 15

A First Program - Greeting.cpp

Introduction to Programming EC-105. Lecture 2

Fundamentals of Programming CS-110. Lecture 2

By the end of this section you should: Understand what the variables are and why they are used. Use C++ built in data types to create program

Lab # 02. Basic Elements of C++ _ Part1

The C++ Language. Arizona State University 1

Chapter 1 INTRODUCTION

1) What of the following sets of values for A, B, C, and D would cause the string "one" to be printed?

Pointers II. Class 31

REVIEW. The C++ Programming Language. CS 151 Review #2

Object Oriented Programming

BITG 1233: Introduction to C++

C++ Programming: From Problem Analysis to Program Design, Third Edition

C++ Exception Handling 1

CSCE 206: Structured Programming in C++

CSCE 206: Structured Programming in C++

Superior University. Department of Electrical Engineering CS-115. Computing Fundamentals. Experiment No.1

University of Technology. Laser & Optoelectronics Engineering Department. C++ Lab.

Exception Handling in C++

The format for declaring function templates with type parameters

2 nd Week Lecture Notes

IT 1033: Fundamentals of Programming Data types & variables

Exception handling. Aishy Amer. Lecture Outline: Introduction Types or errors or exceptions Conventional error processing Exception handling in C++

1- Write a single C++ statement that: A. Calculates the sum of the two integrates 11 and 12 and outputs the sum to the consol.

Week 2: Console I/O and Operators Arithmetic Operators. Integer Division. Arithmetic Operators. Gaddis: Chapter 3 (2.14,3.1-6,3.9-10,5.

Engineering Problem Solving with C++, 3e Chapter 2 Test Bank

Computer Programming : C++

PIC 10A Pointers, Arrays, and Dynamic Memory Allocation. Ernest Ryu UCLA Mathematics

The sequence of steps to be performed in order to solve a problem by the computer is known as an algorithm.

What we will learn about this week: Declaring and referencing arrays. arrays as function arguments. Arrays

Chapter 2. C++ Basics. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

Chapter 2. C++ Basics

Chapter 3 Problem Solving and the Computer

Overview. - General Data Types - Categories of Words. - Define Before Use. - The Three S s. - End of Statement - My First Program

Pointers. Variable Declaration. Chapter 10

Chapter 2. C++ Basics. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

Sahaj Computer Solutions OOPS WITH C++

Multiple Choice (Questions 1 13) 26 Points Select all correct answers (multiple correct answers are possible)

Lab Instructor : Jean Lai

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 8/19/ Review. Here s a simple C++ program:

Programming in C++: Assignment Week 8

! Errors can be dealt with at place error occurs

Intro to Programming & C Why Program? 1.2 Computer Systems: Hardware and Software. Why Learn to Program?

Today in CS161. Lecture #7. Learn about. Rewrite our First Program. Create new Graphics Demos. If and else statements. Using if and else statements

G52CPP C++ Programming Lecture 16

Computer Programming

CAAM 420 Fall 2012 Lecture 29. Duncan Eddy

C++ Structures Programming Workshop 2 (CSCI 1061U)

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 1/9/ Review. Here s a simple C++ program:

IS 0020 Program Design and Software Tools

Extending Classes (contd.) (Chapter 15) Questions:

The American University in Cairo Computer Science & Engineering Department CSCE Dr. KHALIL Exam II Spring 2010

Data type of a pointer must be same as the data type of the variable to which the pointer variable is pointing. Here are a few examples:

1. Match each of the following data types with literal constants of that data type. A data type can be used more than once. A.

The following expression causes a divide by zero error:

I BCS-031 BACHELOR OF COMPUTER APPLICATIONS (BCA) (Revised) Term-End Examination. June, 2015 BCS-031 : PROGRAMMING IN C ++

Non-numeric types, boolean types, arithmetic. operators. Comp Sci 1570 Introduction to C++ Non-numeric types. const. Reserved words.

Input And Output of C++

Informatica 3. Marcello Restelli. Laurea in Ingegneria Informatica Politecnico di Milano 9/15/07 10/29/07

Exception Handling in Java. An Exception is a compile time / runtime error that breaks off the

1st Midterm Exam: Solution COEN 243: Programming Methodology I

C++ For Science and Engineering Lecture 12

Functions in C++ Problem-Solving Procedure With Modular Design C ++ Function Definition: a single

Understanding main() function Input/Output Streams

Chapter 2 C++ Fundamentals

The American University in Cairo Department of Computer Science & Engineering CSCI &09 Dr. KHALIL Exam-I Fall 2011

Programming Language. Functions. Eng. Anis Nazer First Semester

Chapter 17 - Notes Recursion

EE 109 Lab 8a Conversion Experience

Pointers. Reference operator (&) ted = &andy;

Unit 7. 'while' Loops

CSc Introduction to Computing

o Counter and sentinel controlled loops o Formatting output o Type casting o Top-down, stepwise refinement

CS31 Discussion 1E. Jie(Jay) Wang Week1 Sept. 30

Transcription:

Exception Handling

Introduction : Fundamental Syntax for Exception Handling code : try catch throw Multiple exceptions Exception with arguments

Introduction Exception: An abnormal condition that arises in a code sequence at run time. An exception is a run-time error. Exception handling allows us to manage run-time errors in an orderly fashion.

Introduction #include <iostream> using namespace std; int main() double a, b, c; // Request two numbers from the user cout << "Please provide two numbers\n"; cout << "First Number: "; cin >> a; cout << "Second Number: "; cin >> b; // Multiply the numbers and display the result c = a * b; cout << "\n" << a << " * " << b << " = " << c << "\n\n"; return 0;

Introduction When it comes up, the user is asked to simply type two numbers; the program would use them to perform a multiplication and display the result. Imagine that a user, decides to type the name of a country or somebody s telephone number as one of the requested values. Since a program such as this one is not prepared to multiply two strings or one number to a string it would not know what to do.

Introduction The only alternative the compiler would have is to send the problem to the operating system, hoping that the OS would know what to do. Whenever the compiler is handed a task, it would try to perform the assignment. If it can t perform the assignment, for any reason it is not prepared for, it would throw an error. As a programmer, if you can anticipate the type of error that could occur in your program, you can catch the error yourself and deal with it by telling the compiler what to do when this type of error occurs.

Introduction An exception is a situation that would be unusual for the program that is being processed. An error result or an unpredictable behavior on your program not caused by the operating system but that occurs in your program is called an exception. The ability to deal with a program s eventual abnormal behavior is called exception handling.

Introduction Using exception handling, our program can automatically invoke an error-handling routine when an error occurs. C++ exception handling is built upon three keywords: try, catch, and throw.

The Basics try identifies a code block where exception can occur throw causes an exception to be raised (thrown) catch identifies a code block where the exception will be handled (caught) try throw an exception catch the exception 9

Exception Handling Fundamentals..try Error prone program statements that we may want to monitor for generation of exceptions are contained in a try block. Syntax: try // try block

Exception Handling Fundamentals..try When an exception is thrown, the remaining code in the try block is skipped, just as in the case of the return statement in a function, and every auto object created after the try block is entered, is destroyed automatically The thrown object is caught by the catch block where the execution continues Then, the execution continues with the next statement after the catch block

Exception Handling Fundamentals throw If an exception (i.e., an error) occurs within the try block, then that exception is thrown using throw. Syntax: throw exception; If an exception is to be caught, then throw must be executed either from within a try block or from any function called from within the try block (directly or indirectly).

Exception Handling Fundamentals catch The thrown exception is caught, using catch block and processed. Syntax: catch (type argument) // catch block

Catching Exceptions You must supply at least one catch block for a try block Otherwise compiler error (let's see it in ExceptionSample1.cpp). int main() int height; cin >> height; try if (height > 300) throw "height exceeds maximum"; if (height < 30) throw "height below minimum"; cout << "Person is " <<ToInches(height) << "inches tall" << endl; //NO CATCH HERE NOT ALLOWED return 0;

return 0; Catching Exceptions Catch blocks must immediately follow the try block without any program code between them. Otherwise, compiler error (let's see it in ExceptionSample1.cpp). int main() int height; cin >> height; try if (height > 300) throw "height exceeds maximum"; if (height < 30) throw "height below minimum"; cout << "Person is " <<ToInches(height) << "inches tall" << endl; cout << "Wassup"; //no statements are allowed between try and catch catch(const char msg[]) cout << "Exception occured: "<< msg << endl; cout << "Program Stops " << endl;

try Program statements requires monitor for exceptions catch( type argument ) Program statements handles for Exception

try Program statements requires monitor for exceptions catch( type1 argument ) catch( type2 argument ) catch( typen argument ) Program statements handles Program for Exception statements handles for Exception Program statements handles for Exception

Using try & catch try int d = 0; int a = 30 / d; throws Arithmetic Exception catch(int e ) printf("division by zero.");

Syntax for Exception Handling Code : try-catch Combined with the try block, the syntax of an exception would be: try.. throw exception; catch(argument) // Catch the exception

Exception Handling Fundamentals NOTE: Throwing an unhandled exception causes the standard library function terminate() to be invoked. By default, terminate() calls abort() to stop your program.

Code : try- catch-throw #include <iostream> using namespace std; int main() int StudentAge; cout << Enter Student Age: "; cin >> StudentAge; try if(studentage < 0) throw; cout << "\nstudent Age: " << StudentAge << "\n\n";

catch(...) cout << "\n"; return 0; Code : try- catch-throw catch (...) is used to catch any unhandled exception

If positive integer is given as input Output : Enter Student Age: 1 Student Age: 1 Output If negative integer is given as input Output : Enter Student Age: -1 Program will give an abnormal termination error

Code : try- catch-throw #include <iostream> using namespace std; int main() double Number1, Number2, Result; // Request two numbers from the user cout << "Please provide two numbers\n";

Code : try- catch-throw try cout << "First Number: "; cin >> Number1; cout << "Second Number: "; cin >> Number2; if( Number2 == 0 ) throw (Number2); // Perform a division and display the result Result = Number1 / Number2; cout << "\n" << Number1 << " / " << Number2 << " = " << Result << "\n\n";

Code : try- catch-throw catch(int i) cout<< Exception caught : x = <<x<< \n ; return 0;

Output Please provide two numbers First Number: 126.45 Second Number: 5.52 126.45 / 5.52 = 22.9076 Number1 126.45 Number2: 5.52 Result 22.9076

Output Please provide two numbers First Number: 126.45 Second Number: 0 Exception caught : x=0