SlideShare ist ein Scribd-Unternehmen logo
1 von 4
Downloaden Sie, um offline zu lesen
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;
}

Weitere ähnliche Inhalte

Was ist angesagt?

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
 

Was ist angesagt? (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
 

Andere mochten auch

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
 

Andere mochten auch (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
 

Ähnlich wie 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
 

Ähnlich wie 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
 

Mehr von . .

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. .
 

Mehr von . . (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
 

Kürzlich hochgeladen

GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
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 WorkerThousandEyes
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesBoston Institute of Analytics
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
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
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsRoshan Dwivedi
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024SynarionITSolutions
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
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 Scriptwesley chun
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 

Kürzlich hochgeladen (20)

GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
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
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
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
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
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
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 

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