SlideShare una empresa de Scribd logo
1 de 4
Descargar para leer sin conexión
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;
}

Más contenido relacionado

La actualidad más candente

Exceptionhandling
ExceptionhandlingExceptionhandling
ExceptionhandlingNuha Noor
 
exception handling in java
exception handling in java exception handling in java
exception handling in java aptechsravan
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in javapooja kumari
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in javaARAFAT ISLAM
 
14 exception handling
14 exception handling14 exception handling
14 exception handlingjigeno
 
Java Exception Handling and Applets
Java Exception Handling and AppletsJava Exception Handling and Applets
Java Exception Handling and AppletsTanmoy Roy
 
Chap2 exception handling
Chap2 exception handlingChap2 exception handling
Chap2 exception handlingraksharao
 
L14 exception handling
L14 exception handlingL14 exception handling
L14 exception handlingteach4uin
 
Exception handling
Exception handlingException handling
Exception handlingRaja Sekhar
 
Java exception handling
Java exception handlingJava exception handling
Java exception handlingBHUVIJAYAVELU
 
Best Practices in Exception Handling
Best Practices in Exception HandlingBest Practices in Exception Handling
Best Practices in Exception HandlingLemi Orhan Ergin
 
Exception Handling
Exception HandlingException Handling
Exception HandlingReddhi Basu
 

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

Destacado

Core java 9
Core java 9Core java 9
Core java 9. .
 
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ìnhindochinasp
 
Ky thuat l.trinh_java
Ky thuat l.trinh_javaKy thuat l.trinh_java
Ky thuat l.trinh_javaLam Man
 
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 matVũ Sang
 
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 trinhSP Tin K34
 
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ếf3vthd
 
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)Đông Lương
 
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 )Đông Lương
 
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ànhAnh Nguyen
 

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

Similar a Exceptions ref

Interface andexceptions
Interface andexceptionsInterface andexceptions
Interface andexceptionssaman Iftikhar
 
Unit 4 exceptions and threads
Unit 4 exceptions and threadsUnit 4 exceptions and threads
Unit 4 exceptions and threadsDevaKumari Vijay
 
Exception Handling Mechanism in .NET CLR
Exception Handling Mechanism in .NET CLRException Handling Mechanism in .NET CLR
Exception Handling Mechanism in .NET CLRKiran Munir
 
Exception handling
Exception handlingException handling
Exception handlingWaqas Abbasi
 
MODULE5_EXCEPTION HANDLING.docx
MODULE5_EXCEPTION HANDLING.docxMODULE5_EXCEPTION HANDLING.docx
MODULE5_EXCEPTION HANDLING.docxVeerannaKotagi1
 
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.pptxestorebackupr
 
Exceptions
ExceptionsExceptions
Exceptionsmotthu18
 
Exception Handling
Exception HandlingException Handling
Exception HandlingPRN USM
 
Rethrowing exception- JAVA
Rethrowing exception- JAVARethrowing exception- JAVA
Rethrowing exception- JAVARajan Shah
 
Exception handling, Stream Classes, Multithread Programming
Exception handling, Stream Classes, Multithread ProgrammingException handling, Stream Classes, Multithread Programming
Exception handling, Stream Classes, Multithread ProgrammingPrabu U
 
Week7 exception handling
Week7 exception handlingWeek7 exception handling
Week7 exception handlingAlpesh Oza
 
Week7 exception handling
Week7 exception handlingWeek7 exception handling
Week7 exception handlingAlpesh Oza
 
Week7 exception handling
Week7 exception handlingWeek7 exception handling
Week7 exception handlingAlpesh Oza
 
Md07 exceptions&assertion
Md07 exceptions&assertionMd07 exceptions&assertion
Md07 exceptions&assertionRakesh Madugula
 

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

Más 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. .
 

Más 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
 

Último

08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
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 2024Rafal Los
 
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 interpreternaman860154
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
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.pptxEarley Information Science
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
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 2024The Digital Insurer
 
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...Igalia
 
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?Igalia
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
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 Processorsdebabhi2
 

Último (20)

08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
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
 
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
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
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 future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
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
 
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...
 
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?
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
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
 

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; }