SlideShare une entreprise Scribd logo
1  sur  4
Télécharger pour lire hors ligne
http://www.cplusplus.com/doc/tutorial/exceptions/
Exceptions
Exceptions provide a way to react to exceptional circumstances (like runtime errors) in our program by transferring control
to special functions called handlers.
To catch exceptions we must place a portion of code under exception inspection. This is done by enclosing that portion of
code in a try block. When an exceptional circumstance arises within that block, an exception is thrown that transfers the
control to the exception handler. If no exception is thrown, the code continues normally and all handlers are ignored.
An exception is thrown by using the throw keyword from inside the try block. Exception handlers are declared with the
keyword catch, which must be placed immediately after the try block:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// exceptions
#include <iostream>
using namespace std;
int main () {
try
{
throw 20;
}
catch (int e)
{
cout << "An exception occurred. Exception Nr. " << e
<< endl;
}
return 0;
}
An exception occurred. Exception
Nr. 20
The code under exception handling is enclosed in a try block. In this example this code simply throws an exception:
throw 20;
A throw expression accepts one parameter (in this case the integer value 20), which is passed as an argument to the
exception handler.
The exception handler is declared with the catch keyword. As you can see, it follows immediately the closing brace of
the try block. The catch format is similar to a regular function that always has at least one parameter. The type of this
parameter is very important, since the type of the argument passed by the throw expression is checked against it, and only
in the case they match, the exception is caught.
We can chain multiple handlers (catch expressions), each one with a different parameter type. Only the handler that
matches its type with the argument specified in the throw statement is executed.
If we use an ellipsis (...) as the parameter of catch, that handler will catch any exception no matter what the type of
the throw exception is. This can be used as a default handler that catches all exceptions not caught by other handlers if it is
specified at last:
1
2
3
4
5
try {
// code here
}
catch (int param) { cout << "int exception"; }
catch (char param) { cout << "char exception"; }
http://www.cplusplus.com/doc/tutorial/exceptions/
6 catch (...) { cout << "default exception"; }
In this case the last handler would catch any exception thrown with any parameter that is neither an int nor achar.
After an exception has been handled the program execution resumes after the try-catch block, not after
the throwstatement!.
It is also possible to nest try-catch blocks within more external try blocks. In these cases, we have the possibility that an
internal catch block forwards the exception to its external level. This is done with the expression throw;with no arguments.
For example:
1
2
3
4
5
6
7
8
9
10
11
try {
try {
// code here
}
catch (int n) {
throw;
}
}
catch (...) {
cout << "Exception occurred";
}
Exception specifications
When declaring a function we can limit the exception type it might directly or indirectly throw by appending a throwsuffix to
the function declaration:
float myfunction (char param) throw (int);
This declares a function called myfunction which takes one argument of type char and returns an element of typefloat.
The only exception that this function might throw is an exception of type int. If it throws an exception with a different type,
either directly or indirectly, it cannot be caught by a regular int-type handler.
If this throw specifier is left empty with no type, this means the function is not allowed to throw exceptions. Functions with
no throw specifier (regular functions) are allowed to throw exceptions with any type:
1
2
int myfunction (int param) throw(); // no exceptions allowed
int myfunction (int param); // all exceptions allowed
Standard exceptions
The C++ Standard library provides a base class specifically designed to declare objects to be thrown as exceptions. It is
called exception and is defined in the <exception> header file under the namespace std. This class has the usual default
http://www.cplusplus.com/doc/tutorial/exceptions/
and copy constructors, operators and destructors, plus an additional virtual member function called what that returns a null-
terminated character sequence (char *) and that can be overwritten in derived classes to contain some sort of description of
the exception.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// standard exceptions
#include <iostream>
#include <exception>
using namespace std;
class myexception: public exception
{
virtual const char* what() const throw()
{
return "My exception happened";
}
} myex;
int main () {
try
{
throw myex;
}
catch (exception& e)
{
cout << e.what() << endl;
}
return 0;
}
My exception happened.
We have placed a handler that catches exception objects by reference (notice the ampersand & after the type), therefore this
catches also classes derived from exception, like our myex object of class myexception.
All exceptions thrown by components of the C++ Standard library throw exceptions derived from thisstd::exception class.
These are:
exception description
bad_alloc thrown by new on allocation failure
bad_cast thrown by dynamic_cast when fails with a referenced type
bad_exception thrown when an exception type doesn't match any catch
bad_typeid thrown by typeid
ios_base::failure thrown by functions in the iostream library
For example, if we use the operator new and the memory cannot be allocated, an exception of type bad_alloc is thrown:
1
2
3
4
5
6
7
8
try
{
int * myarray= new int[1000];
}
catch (bad_alloc&)
{
cout << "Error allocating memory." << endl;
}
http://www.cplusplus.com/doc/tutorial/exceptions/
It is recommended to include all dynamic memory allocations within a try block that catches this type of exception to
perform a clean action instead of an abnormal program termination, which is what happens when this type of exception is
thrown and not caught. If you want to force a bad_alloc exception to see it in action, you can try to allocate a huge array;
On my system, trying to allocate 1 billion ints threw a bad_alloc exception.
Because bad_alloc is derived from the standard base class exception, we can handle that same exception by catching
references to the exception class:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// bad_alloc standard exception
#include <iostream>
#include <exception>
using namespace std;
int main () {
try
{
int* myarray= new int[1000];
}
catch (exception& e)
{
cout << "Standard exception: " << e.what()
<< endl;
}
return 0;
}

Contenu connexe

Tendances

exception handling in java
exception handling in java exception handling in java
exception handling in java
aptechsravan
 
14 exception handling
14 exception handling14 exception handling
14 exception handling
jigeno
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
BHUVIJAYAVELU
 

Tendances (20)

Exceptionhandling
ExceptionhandlingExceptionhandling
Exceptionhandling
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
exception handling in java
exception handling in java exception handling in java
exception handling in java
 
Exception handling
Exception handling Exception handling
Exception handling
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Exception handling
Exception handlingException handling
Exception handling
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Built in exceptions
Built in exceptions Built in exceptions
Built in exceptions
 
14 exception handling
14 exception handling14 exception handling
14 exception handling
 
Java Exception Handling and Applets
Java Exception Handling and AppletsJava Exception Handling and Applets
Java Exception Handling and Applets
 
Chap2 exception handling
Chap2 exception handlingChap2 exception handling
Chap2 exception handling
 
Exception handling in Java
Exception handling in JavaException handling in Java
Exception handling in Java
 
Java exception
Java exception Java exception
Java exception
 
Exception Handling in Java
Exception Handling in JavaException Handling in Java
Exception Handling in Java
 
L14 exception handling
L14 exception handlingL14 exception handling
L14 exception handling
 
Exception
ExceptionException
Exception
 
Exception handling
Exception handlingException handling
Exception handling
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
 
Best Practices in Exception Handling
Best Practices in Exception HandlingBest Practices in Exception Handling
Best Practices in Exception Handling
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 

En vedette (20)

Java2 studyguide 2012
Java2 studyguide 2012Java2 studyguide 2012
Java2 studyguide 2012
 
Core java 9
Core java 9Core java 9
Core java 9
 
Laptrinh java
Laptrinh javaLaptrinh java
Laptrinh java
 
Bài 3: Cấu trúc chương trình
Bài 3: Cấu trúc chương trìnhBài 3: Cấu trúc chương trình
Bài 3: Cấu trúc chương trình
 
Ky thuat l.trinh_java
Ky thuat l.trinh_javaKy thuat l.trinh_java
Ky thuat l.trinh_java
 
Core java 1
Core java 1Core java 1
Core java 1
 
Core java 5
Core java 5Core java 5
Core java 5
 
Core java 4
Core java 4Core java 4
Core java 4
 
Bai10 he thong bao ve bao mat
Bai10   he thong bao ve bao matBai10   he thong bao ve bao mat
Bai10 he thong bao ve bao mat
 
Core java 7
Core java 7Core java 7
Core java 7
 
Core java 3
Core java 3Core java 3
Core java 3
 
Core java 10
Core java 10Core java 10
Core java 10
 
Nguyen le hien duyen tin hoc 11 - bai 3 - cau truc chuong trinh
Nguyen le hien duyen   tin hoc 11 - bai 3 - cau truc chuong trinhNguyen le hien duyen   tin hoc 11 - bai 3 - cau truc chuong trinh
Nguyen le hien duyen tin hoc 11 - bai 3 - cau truc chuong trinh
 
Core java 2
Core java 2Core java 2
Core java 2
 
Lập trình hướng đối tượng với Java - Trần Đình Quế
Lập trình hướng đối tượng với Java  - Trần Đình QuếLập trình hướng đối tượng với Java  - Trần Đình Quế
Lập trình hướng đối tượng với Java - Trần Đình Quế
 
Core java 6
Core java 6Core java 6
Core java 6
 
Giáo Trình Java Cơ Bản ( Vietnamese)
Giáo Trình Java Cơ Bản ( Vietnamese)Giáo Trình Java Cơ Bản ( Vietnamese)
Giáo Trình Java Cơ Bản ( Vietnamese)
 
Laptrinh jdbc
Laptrinh jdbcLaptrinh jdbc
Laptrinh jdbc
 
Lập Trình Hướng Đối Tượng trong Java ( Vietnamese )
Lập Trình Hướng Đối Tượng trong Java ( Vietnamese )Lập Trình Hướng Đối Tượng trong Java ( Vietnamese )
Lập Trình Hướng Đối Tượng trong Java ( Vietnamese )
 
Bài 12: Giao tiếp với hệ điều hành
Bài 12: Giao tiếp với hệ điều hànhBài 12: Giao tiếp với hệ điều hành
Bài 12: Giao tiếp với hệ điều hành
 

Similaire à Exceptions ref

Exception Handling Mechanism in .NET CLR
Exception Handling Mechanism in .NET CLRException Handling Mechanism in .NET CLR
Exception Handling Mechanism in .NET CLR
Kiran Munir
 
Week7 exception handling
Week7 exception handlingWeek7 exception handling
Week7 exception handling
Alpesh Oza
 
Week7 exception handling
Week7 exception handlingWeek7 exception handling
Week7 exception handling
Alpesh Oza
 
Md07 exceptions&assertion
Md07 exceptions&assertionMd07 exceptions&assertion
Md07 exceptions&assertion
Rakesh Madugula
 

Similaire à Exceptions ref (20)

Exceptions in c++
Exceptions in c++Exceptions in c++
Exceptions in c++
 
Interface andexceptions
Interface andexceptionsInterface andexceptions
Interface andexceptions
 
Z blue exception
Z blue   exceptionZ blue   exception
Z blue exception
 
Java unit3
Java unit3Java unit3
Java unit3
 
Exceptions
ExceptionsExceptions
Exceptions
 
Java unit 11
Java unit 11Java unit 11
Java unit 11
 
Unit 4 exceptions and threads
Unit 4 exceptions and threadsUnit 4 exceptions and threads
Unit 4 exceptions and threads
 
Exception Handling Mechanism in .NET CLR
Exception Handling Mechanism in .NET CLRException Handling Mechanism in .NET CLR
Exception Handling Mechanism in .NET CLR
 
Exception handling
Exception handlingException handling
Exception handling
 
MODULE5_EXCEPTION HANDLING.docx
MODULE5_EXCEPTION HANDLING.docxMODULE5_EXCEPTION HANDLING.docx
MODULE5_EXCEPTION HANDLING.docx
 
Exceptions in C++ Object Oriented Programming.pptx
Exceptions in C++ Object Oriented Programming.pptxExceptions in C++ Object Oriented Programming.pptx
Exceptions in C++ Object Oriented Programming.pptx
 
Exceptions
ExceptionsExceptions
Exceptions
 
Handling
HandlingHandling
Handling
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
Rethrowing exception- JAVA
Rethrowing exception- JAVARethrowing exception- JAVA
Rethrowing exception- JAVA
 
Exception handling, Stream Classes, Multithread Programming
Exception handling, Stream Classes, Multithread ProgrammingException handling, Stream Classes, Multithread Programming
Exception handling, Stream Classes, Multithread Programming
 
Week7 exception handling
Week7 exception handlingWeek7 exception handling
Week7 exception handling
 
Week7 exception handling
Week7 exception handlingWeek7 exception handling
Week7 exception handling
 
Week7 exception handling
Week7 exception handlingWeek7 exception handling
Week7 exception handling
 
Md07 exceptions&assertion
Md07 exceptions&assertionMd07 exceptions&assertion
Md07 exceptions&assertion
 

Plus de . .

Cq lt hdt-th2011-01-tuan11
Cq lt hdt-th2011-01-tuan11Cq lt hdt-th2011-01-tuan11
Cq lt hdt-th2011-01-tuan11
. .
 
Cq lt hdt-th2011-01-tuan10
Cq lt hdt-th2011-01-tuan10Cq lt hdt-th2011-01-tuan10
Cq lt hdt-th2011-01-tuan10
. .
 
Cq lt hdt-th2011-01-tuan09
Cq lt hdt-th2011-01-tuan09Cq lt hdt-th2011-01-tuan09
Cq lt hdt-th2011-01-tuan09
. .
 
Cq lt hdt-th2011-01-tuan08
Cq lt hdt-th2011-01-tuan08Cq lt hdt-th2011-01-tuan08
Cq lt hdt-th2011-01-tuan08
. .
 
Cq lt hdt-th2011-01-tuan05
Cq lt hdt-th2011-01-tuan05Cq lt hdt-th2011-01-tuan05
Cq lt hdt-th2011-01-tuan05
. .
 
Cq lt hdt-th2011-01-tuan02
Cq lt hdt-th2011-01-tuan02Cq lt hdt-th2011-01-tuan02
Cq lt hdt-th2011-01-tuan02
. .
 
Cq lt hdt-th2011-01-tuan01
Cq lt hdt-th2011-01-tuan01Cq lt hdt-th2011-01-tuan01
Cq lt hdt-th2011-01-tuan01
. .
 
Cq lt hdt-th2011-01-thck
Cq lt hdt-th2011-01-thckCq lt hdt-th2011-01-thck
Cq lt hdt-th2011-01-thck
. .
 
Cq lt hdt-th2011-02-tuan04
Cq lt hdt-th2011-02-tuan04Cq lt hdt-th2011-02-tuan04
Cq lt hdt-th2011-02-tuan04
. .
 
Cautrucdulieu full
Cautrucdulieu fullCautrucdulieu full
Cautrucdulieu full
. .
 
Baitaprdbms
BaitaprdbmsBaitaprdbms
Baitaprdbms
. .
 
Bai tap va loi giai sql
Bai tap va loi giai sqlBai tap va loi giai sql
Bai tap va loi giai sql
. .
 
Cau lenh truy_van_sql
Cau lenh truy_van_sqlCau lenh truy_van_sql
Cau lenh truy_van_sql
. .
 
Core java 8
Core java 8Core java 8
Core java 8
. .
 
ToanRoirac
ToanRoiracToanRoirac
ToanRoirac
. .
 

Plus de . . (15)

Cq lt hdt-th2011-01-tuan11
Cq lt hdt-th2011-01-tuan11Cq lt hdt-th2011-01-tuan11
Cq lt hdt-th2011-01-tuan11
 
Cq lt hdt-th2011-01-tuan10
Cq lt hdt-th2011-01-tuan10Cq lt hdt-th2011-01-tuan10
Cq lt hdt-th2011-01-tuan10
 
Cq lt hdt-th2011-01-tuan09
Cq lt hdt-th2011-01-tuan09Cq lt hdt-th2011-01-tuan09
Cq lt hdt-th2011-01-tuan09
 
Cq lt hdt-th2011-01-tuan08
Cq lt hdt-th2011-01-tuan08Cq lt hdt-th2011-01-tuan08
Cq lt hdt-th2011-01-tuan08
 
Cq lt hdt-th2011-01-tuan05
Cq lt hdt-th2011-01-tuan05Cq lt hdt-th2011-01-tuan05
Cq lt hdt-th2011-01-tuan05
 
Cq lt hdt-th2011-01-tuan02
Cq lt hdt-th2011-01-tuan02Cq lt hdt-th2011-01-tuan02
Cq lt hdt-th2011-01-tuan02
 
Cq lt hdt-th2011-01-tuan01
Cq lt hdt-th2011-01-tuan01Cq lt hdt-th2011-01-tuan01
Cq lt hdt-th2011-01-tuan01
 
Cq lt hdt-th2011-01-thck
Cq lt hdt-th2011-01-thckCq lt hdt-th2011-01-thck
Cq lt hdt-th2011-01-thck
 
Cq lt hdt-th2011-02-tuan04
Cq lt hdt-th2011-02-tuan04Cq lt hdt-th2011-02-tuan04
Cq lt hdt-th2011-02-tuan04
 
Cautrucdulieu full
Cautrucdulieu fullCautrucdulieu full
Cautrucdulieu full
 
Baitaprdbms
BaitaprdbmsBaitaprdbms
Baitaprdbms
 
Bai tap va loi giai sql
Bai tap va loi giai sqlBai tap va loi giai sql
Bai tap va loi giai sql
 
Cau lenh truy_van_sql
Cau lenh truy_van_sqlCau lenh truy_van_sql
Cau lenh truy_van_sql
 
Core java 8
Core java 8Core java 8
Core java 8
 
ToanRoirac
ToanRoiracToanRoirac
ToanRoirac
 

Dernier

EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
Earley Information Science
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
giselly40
 

Dernier (20)

Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
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...
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
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
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
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
 

Exceptions ref

  • 1. http://www.cplusplus.com/doc/tutorial/exceptions/ Exceptions Exceptions provide a way to react to exceptional circumstances (like runtime errors) in our program by transferring control to special functions called handlers. To catch exceptions we must place a portion of code under exception inspection. This is done by enclosing that portion of code in a try block. When an exceptional circumstance arises within that block, an exception is thrown that transfers the control to the exception handler. If no exception is thrown, the code continues normally and all handlers are ignored. An exception is thrown by using the throw keyword from inside the try block. Exception handlers are declared with the keyword catch, which must be placed immediately after the try block: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 // exceptions #include <iostream> using namespace std; int main () { try { throw 20; } catch (int e) { cout << "An exception occurred. Exception Nr. " << e << endl; } return 0; } An exception occurred. Exception Nr. 20 The code under exception handling is enclosed in a try block. In this example this code simply throws an exception: throw 20; A throw expression accepts one parameter (in this case the integer value 20), which is passed as an argument to the exception handler. The exception handler is declared with the catch keyword. As you can see, it follows immediately the closing brace of the try block. The catch format is similar to a regular function that always has at least one parameter. The type of this parameter is very important, since the type of the argument passed by the throw expression is checked against it, and only in the case they match, the exception is caught. We can chain multiple handlers (catch expressions), each one with a different parameter type. Only the handler that matches its type with the argument specified in the throw statement is executed. If we use an ellipsis (...) as the parameter of catch, that handler will catch any exception no matter what the type of the throw exception is. This can be used as a default handler that catches all exceptions not caught by other handlers if it is specified at last: 1 2 3 4 5 try { // code here } catch (int param) { cout << "int exception"; } catch (char param) { cout << "char exception"; }
  • 2. http://www.cplusplus.com/doc/tutorial/exceptions/ 6 catch (...) { cout << "default exception"; } In this case the last handler would catch any exception thrown with any parameter that is neither an int nor achar. After an exception has been handled the program execution resumes after the try-catch block, not after the throwstatement!. It is also possible to nest try-catch blocks within more external try blocks. In these cases, we have the possibility that an internal catch block forwards the exception to its external level. This is done with the expression throw;with no arguments. For example: 1 2 3 4 5 6 7 8 9 10 11 try { try { // code here } catch (int n) { throw; } } catch (...) { cout << "Exception occurred"; } Exception specifications When declaring a function we can limit the exception type it might directly or indirectly throw by appending a throwsuffix to the function declaration: float myfunction (char param) throw (int); This declares a function called myfunction which takes one argument of type char and returns an element of typefloat. The only exception that this function might throw is an exception of type int. If it throws an exception with a different type, either directly or indirectly, it cannot be caught by a regular int-type handler. If this throw specifier is left empty with no type, this means the function is not allowed to throw exceptions. Functions with no throw specifier (regular functions) are allowed to throw exceptions with any type: 1 2 int myfunction (int param) throw(); // no exceptions allowed int myfunction (int param); // all exceptions allowed Standard exceptions The C++ Standard library provides a base class specifically designed to declare objects to be thrown as exceptions. It is called exception and is defined in the <exception> header file under the namespace std. This class has the usual default
  • 3. http://www.cplusplus.com/doc/tutorial/exceptions/ and copy constructors, operators and destructors, plus an additional virtual member function called what that returns a null- terminated character sequence (char *) and that can be overwritten in derived classes to contain some sort of description of the exception. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 // standard exceptions #include <iostream> #include <exception> using namespace std; class myexception: public exception { virtual const char* what() const throw() { return "My exception happened"; } } myex; int main () { try { throw myex; } catch (exception& e) { cout << e.what() << endl; } return 0; } My exception happened. We have placed a handler that catches exception objects by reference (notice the ampersand & after the type), therefore this catches also classes derived from exception, like our myex object of class myexception. All exceptions thrown by components of the C++ Standard library throw exceptions derived from thisstd::exception class. These are: exception description bad_alloc thrown by new on allocation failure bad_cast thrown by dynamic_cast when fails with a referenced type bad_exception thrown when an exception type doesn't match any catch bad_typeid thrown by typeid ios_base::failure thrown by functions in the iostream library For example, if we use the operator new and the memory cannot be allocated, an exception of type bad_alloc is thrown: 1 2 3 4 5 6 7 8 try { int * myarray= new int[1000]; } catch (bad_alloc&) { cout << "Error allocating memory." << endl; }
  • 4. http://www.cplusplus.com/doc/tutorial/exceptions/ It is recommended to include all dynamic memory allocations within a try block that catches this type of exception to perform a clean action instead of an abnormal program termination, which is what happens when this type of exception is thrown and not caught. If you want to force a bad_alloc exception to see it in action, you can try to allocate a huge array; On my system, trying to allocate 1 billion ints threw a bad_alloc exception. Because bad_alloc is derived from the standard base class exception, we can handle that same exception by catching references to the exception class: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 // bad_alloc standard exception #include <iostream> #include <exception> using namespace std; int main () { try { int* myarray= new int[1000]; } catch (exception& e) { cout << "Standard exception: " << e.what() << endl; } return 0; }