This document discusses exception handling in C++. It begins with an introduction explaining that exception handling allows a program to automatically invoke error handling routines when runtime errors occur. It then covers key aspects of exception handling including the try, catch, and throw statements. Finally, it provides code examples demonstrating how to throw, catch, and handle exceptions in C++.
The document discusses exception handling in programming. It defines an exception as an unexpected event that disrupts normal program flow, such as divide-by-zero errors. Exception handling allows programs to deal with anomalous situations through try-catch blocks. Code that could cause errors is placed in a try block, while catch blocks handle any exceptions thrown. The document provides examples of exceptions being thrown and caught for issues like invalid inputs, out of memory errors, and array out of bounds.
Exception handling in C# involves using try, catch, and finally blocks. The try block contains code that might throw exceptions, the catch block handles any exceptions, and finally contains cleanup code. There are different types of exceptions like OutOfMemoryException and DivideByZeroException. Exceptions can be handled by showing error messages, logging exceptions, or throwing custom exceptions for business rule violations.
This document discusses exception handling in C++. It covers:
- The principles of exception handling using try, throw, and catch keywords.
- Examples of throwing and catching exceptions of different types.
- Using multiple catch blocks to handle different exception types.
- Rethrowing exceptions in nested try-catch blocks or functions.
- Exceptions in constructors and destructors and how to handle them.
- Uncaught exceptions and how the program terminates if an exception is not caught.
Namespaces can group related code such as classes, objects, and functions to prevent naming collisions. Exceptions provide a way to handle errors and problems that occur in programs by bubbling the error up the call stack. Standard exceptions like bad_alloc are thrown for issues like memory allocation failures. Custom exception classes can be created to specify the type of error. Exception specifications declare what types of exceptions a function is allowed to throw.
The document discusses exception handling in C++. It provides information on key concepts like try, catch, and throw blocks. It also discusses exception classes in C++, defining custom exceptions, and how exceptions affect object destruction. Templates and the Standard Template Library (STL) are also covered at a high level.
Exception handling in C++ allows programs to handle runtime errors and unexpected situations called exceptions. Code that could cause exceptions is placed in a try block. If an exception occurs, it is thrown to a catch block that handles the exception. C++ supports multiple catch blocks to handle different exception types based on the parameters passed to throw. This allows catching specific exceptions while resuming normal execution when no exception occurs.
This document discusses exception handling in C++. It begins with an introduction explaining that exception handling allows a program to automatically invoke error handling routines when runtime errors occur. It then covers key aspects of exception handling including the try, catch, and throw statements. Finally, it provides code examples demonstrating how to throw, catch, and handle exceptions in C++.
The document discusses exception handling in programming. It defines an exception as an unexpected event that disrupts normal program flow, such as divide-by-zero errors. Exception handling allows programs to deal with anomalous situations through try-catch blocks. Code that could cause errors is placed in a try block, while catch blocks handle any exceptions thrown. The document provides examples of exceptions being thrown and caught for issues like invalid inputs, out of memory errors, and array out of bounds.
Exception handling in C# involves using try, catch, and finally blocks. The try block contains code that might throw exceptions, the catch block handles any exceptions, and finally contains cleanup code. There are different types of exceptions like OutOfMemoryException and DivideByZeroException. Exceptions can be handled by showing error messages, logging exceptions, or throwing custom exceptions for business rule violations.
This document discusses exception handling in C++. It covers:
- The principles of exception handling using try, throw, and catch keywords.
- Examples of throwing and catching exceptions of different types.
- Using multiple catch blocks to handle different exception types.
- Rethrowing exceptions in nested try-catch blocks or functions.
- Exceptions in constructors and destructors and how to handle them.
- Uncaught exceptions and how the program terminates if an exception is not caught.
Namespaces can group related code such as classes, objects, and functions to prevent naming collisions. Exceptions provide a way to handle errors and problems that occur in programs by bubbling the error up the call stack. Standard exceptions like bad_alloc are thrown for issues like memory allocation failures. Custom exception classes can be created to specify the type of error. Exception specifications declare what types of exceptions a function is allowed to throw.
The document discusses exception handling in C++. It provides information on key concepts like try, catch, and throw blocks. It also discusses exception classes in C++, defining custom exceptions, and how exceptions affect object destruction. Templates and the Standard Template Library (STL) are also covered at a high level.
Exception handling in C++ allows programs to handle runtime errors and unexpected situations called exceptions. Code that could cause exceptions is placed in a try block. If an exception occurs, it is thrown to a catch block that handles the exception. C++ supports multiple catch blocks to handle different exception types based on the parameters passed to throw. This allows catching specific exceptions while resuming normal execution when no exception occurs.
Exception handling in C++ allows programs to deal with abnormal or unexpected behaviors during execution. It uses three keywords - try, catch, and throw. The try block defines the code that might cause exceptions. If an exception occurs, the program flow moves to the catch block to handle it. Multiple catch blocks can be chained to handle different exception types. The throw keyword transfers control from the try block to the catch block when an exception happens.
This document discusses exception handling in C++ and Java. It defines what exceptions are and explains that exception handling separates error handling code from normal code to make programs more readable and robust. It covers try/catch blocks, throwing and catching exceptions, and exception hierarchies. Finally, it provides an example of implementing exception handling in a C++ program to handle divide-by-zero errors.
Exceptions and Exception Handling in C++IRJET Journal
This document discusses exceptions and exception handling in C++. It begins with an introduction explaining that exceptions are errors that occur during runtime due to unexpected conditions like dividing by zero. It then explains the key concepts of exceptions handling in C++ using try, catch, and throw keywords. Try blocks contain code that may throw exceptions. Catch blocks contain code to handle exceptions. Exceptions are thrown using throw. The document provides examples to demonstrate exception handling mechanisms like catching multiple exception types, and re-throwing exceptions. It also discusses specifying the types of exceptions a function can throw.
Exception handling in Java involves using try, catch, and finally blocks to gracefully handle errors and unexpected conditions at runtime. The try block contains code that might throw exceptions, catch blocks specify how to handle specific exceptions, and finally ensures cleanup code runs regardless of exceptions. User-defined exceptions can be created by subclassing the Exception class and using throw to raise the exception which catch blocks can then handle.
Unit II Java & J2EE regarding Java application developmentrohitgudasi18
This document discusses exception handling and multithreaded programming in Java. It covers exception handling fundamentals including try, catch, throw, throws and finally blocks. It also discusses uncaught exceptions, displaying exception descriptions, and multiple catch clauses. It covers threading fundamentals such as thread priorities, synchronization, and messaging between threads. It discusses the Thread class, Runnable interface, and methods for creating and controlling threads such as start(), sleep(), setName(), and getName().
The document discusses exception handling in C++. It defines exceptions as conditions that occur during execution and prevent normal program continuation. Exception handling involves trying blocks of code that may throw exceptions, throwing exceptions when errors occur, and catching exceptions in handler blocks to deal with the errors. The key aspects of exception handling are try blocks for code that can throw, throw statements to indicate exceptions, and catch blocks that match exception types to handle them.
The document discusses exception handling in Java. It defines exceptions as errors encountered during program execution. Exception handling involves using try, catch, and finally blocks. The try block contains code that may throw exceptions. Catch blocks handle specific exception types, while finally blocks contain cleanup code that always executes. Common system-defined exceptions like NullPointerException and user-defined exceptions can be thrown using the throw keyword and handled using try-catch. Nested try-catch blocks and multiple catch blocks are also described.
The document discusses exception handling in C++. It defines synchronous and asynchronous exceptions and explains the purpose of exceptions is to detect and report exceptional circumstances so appropriate action can be taken. It describes the exception handling mechanism using try, throw, and catch keywords. It explains that exceptions can be rethrown from a catch block to propagate the exception outward. It provides examples of rethrowing an exception and creating a user-defined exception by inheriting from the standard exception class.
This document discusses exception handling in C++. It defines an exception as an event that occurs during program execution that disrupts normal flow, like divide by zero errors. Exception handling allows the program to maintain normal flow even after errors by catching and handling exceptions. It describes the key parts of exception handling as finding problems, throwing exceptions, catching exceptions, and handling exceptions. The document provides examples of using try, catch, and throw blocks to handle exceptions in C++ code.
Exceptions are runtime errors that a program may encounter. There are two types: synchronous from faults in input data, and asynchronous from external events. Exception handling uses try, throw, and catch keywords. Code that may cause exceptions is placed in a try block. When an exception occurs it is thrown, and the catch block handles it to prevent program termination. Multiple catch blocks can handle different exception types, and a catch-all block uses ellipses to catch any exception.
This document provides an overview of exception handling in Java. It defines what exceptions are, common causes of exceptions, and how exception handling works in Java using keywords like try, catch, throw, throws, and finally. It also discusses different exception types, creating custom exceptions, and key classes related to exceptions in the java.util package like Date, TimeZone, Calendar, and GregorianCalendar.
exception handling in C++,
C++ / CPP / C PLUS PLUS notes, object oriented programming using C++ / CPP / C PLUS PLUS, C++ / CPP / C PLUS PLUS tutorial, lecture notes, C++ / CPP / C PLUS PLUS programming notes, C++ / CPP / C PLUS PLUS example programs, C++ / CPP / C PLUS PLUS programs with explanation, C++ / CPP / C PLUS PLUS source code with output, C++ / CPP / C PLUS PLUS programs, C++ / CPP / C PLUS PLUS coding, C++ / CPP / C PLUS PLUS codes, C++ / CPP / C PLUS PLUS slides, C++ / CPP / C PLUS PLUS notes
The document discusses try/catch blocks in Java and how they can be used to handle errors and exceptions. It covers:
1) Using try/catch blocks allows code to fix errors and prevent program termination by handling exceptions.
2) Multiple catch clauses can be specified to handle different exception types thrown from the same code block.
3) Try blocks can be nested, with inner exceptions caught by inner handlers or bubbled up to outer handlers if uncaught.
This document discusses exception handling in C++. It covers try-catch blocks, multiple catch blocks, catch-all blocks, and rethrowing exceptions. Try blocks contain code that may throw exceptions. Catch blocks catch exceptions thrown from try blocks and handle them. Multiple catch blocks allow handling different exception types. Catch-all blocks catch any exception not caught previously. Exceptions can be rethrown using throw to pass handling to outer try-catch blocks.
This document provides an overview of exception handling in Java, including try/catch blocks, checked and unchecked exceptions, custom exceptions, and exception propagation. It defines exceptions as abnormal code conditions, explains how to handle exceptions with try/catch/finally, and covers exception hierarchies, multiple catch blocks, and system-defined vs. programmer-defined exceptions.
The document discusses exception handling and templates in C++. It describes exception handling using try, catch, and throw keywords. It also explains function templates and class templates which allow creating generic functions and classes that can work with different data types.
The document discusses exception handling in Java. It defines different types of errors like logical errors, compilation errors, and runtime errors. It explains checked and unchecked exceptions. It describes how to handle exceptions using try, catch, and finally blocks. It provides examples of handling ArithmeticException and other exceptions. It also discusses multi-catch, throw statement, re-throwing exceptions, and throws keyword to declare exceptions in method signatures.
The document discusses exception handling in C++. It provides examples of throwing exceptions from functions using try/catch blocks. It explains that exceptions allow programs to handle errors and unexpected situations gracefully rather than crashing. The document also discusses catching multiple exception types using multiple catch blocks or a catch-all block. Well-handled exceptions can prevent bugs and make programs more robust.
Exception handling in C++ allows programs to deal with abnormal or unexpected behaviors during execution. It uses three keywords - try, catch, and throw. The try block defines the code that might cause exceptions. If an exception occurs, the program flow moves to the catch block to handle it. Multiple catch blocks can be chained to handle different exception types. The throw keyword transfers control from the try block to the catch block when an exception happens.
This document discusses exception handling in C++ and Java. It defines what exceptions are and explains that exception handling separates error handling code from normal code to make programs more readable and robust. It covers try/catch blocks, throwing and catching exceptions, and exception hierarchies. Finally, it provides an example of implementing exception handling in a C++ program to handle divide-by-zero errors.
Exceptions and Exception Handling in C++IRJET Journal
This document discusses exceptions and exception handling in C++. It begins with an introduction explaining that exceptions are errors that occur during runtime due to unexpected conditions like dividing by zero. It then explains the key concepts of exceptions handling in C++ using try, catch, and throw keywords. Try blocks contain code that may throw exceptions. Catch blocks contain code to handle exceptions. Exceptions are thrown using throw. The document provides examples to demonstrate exception handling mechanisms like catching multiple exception types, and re-throwing exceptions. It also discusses specifying the types of exceptions a function can throw.
Exception handling in Java involves using try, catch, and finally blocks to gracefully handle errors and unexpected conditions at runtime. The try block contains code that might throw exceptions, catch blocks specify how to handle specific exceptions, and finally ensures cleanup code runs regardless of exceptions. User-defined exceptions can be created by subclassing the Exception class and using throw to raise the exception which catch blocks can then handle.
Unit II Java & J2EE regarding Java application developmentrohitgudasi18
This document discusses exception handling and multithreaded programming in Java. It covers exception handling fundamentals including try, catch, throw, throws and finally blocks. It also discusses uncaught exceptions, displaying exception descriptions, and multiple catch clauses. It covers threading fundamentals such as thread priorities, synchronization, and messaging between threads. It discusses the Thread class, Runnable interface, and methods for creating and controlling threads such as start(), sleep(), setName(), and getName().
The document discusses exception handling in C++. It defines exceptions as conditions that occur during execution and prevent normal program continuation. Exception handling involves trying blocks of code that may throw exceptions, throwing exceptions when errors occur, and catching exceptions in handler blocks to deal with the errors. The key aspects of exception handling are try blocks for code that can throw, throw statements to indicate exceptions, and catch blocks that match exception types to handle them.
The document discusses exception handling in Java. It defines exceptions as errors encountered during program execution. Exception handling involves using try, catch, and finally blocks. The try block contains code that may throw exceptions. Catch blocks handle specific exception types, while finally blocks contain cleanup code that always executes. Common system-defined exceptions like NullPointerException and user-defined exceptions can be thrown using the throw keyword and handled using try-catch. Nested try-catch blocks and multiple catch blocks are also described.
The document discusses exception handling in C++. It defines synchronous and asynchronous exceptions and explains the purpose of exceptions is to detect and report exceptional circumstances so appropriate action can be taken. It describes the exception handling mechanism using try, throw, and catch keywords. It explains that exceptions can be rethrown from a catch block to propagate the exception outward. It provides examples of rethrowing an exception and creating a user-defined exception by inheriting from the standard exception class.
This document discusses exception handling in C++. It defines an exception as an event that occurs during program execution that disrupts normal flow, like divide by zero errors. Exception handling allows the program to maintain normal flow even after errors by catching and handling exceptions. It describes the key parts of exception handling as finding problems, throwing exceptions, catching exceptions, and handling exceptions. The document provides examples of using try, catch, and throw blocks to handle exceptions in C++ code.
Exceptions are runtime errors that a program may encounter. There are two types: synchronous from faults in input data, and asynchronous from external events. Exception handling uses try, throw, and catch keywords. Code that may cause exceptions is placed in a try block. When an exception occurs it is thrown, and the catch block handles it to prevent program termination. Multiple catch blocks can handle different exception types, and a catch-all block uses ellipses to catch any exception.
This document provides an overview of exception handling in Java. It defines what exceptions are, common causes of exceptions, and how exception handling works in Java using keywords like try, catch, throw, throws, and finally. It also discusses different exception types, creating custom exceptions, and key classes related to exceptions in the java.util package like Date, TimeZone, Calendar, and GregorianCalendar.
exception handling in C++,
C++ / CPP / C PLUS PLUS notes, object oriented programming using C++ / CPP / C PLUS PLUS, C++ / CPP / C PLUS PLUS tutorial, lecture notes, C++ / CPP / C PLUS PLUS programming notes, C++ / CPP / C PLUS PLUS example programs, C++ / CPP / C PLUS PLUS programs with explanation, C++ / CPP / C PLUS PLUS source code with output, C++ / CPP / C PLUS PLUS programs, C++ / CPP / C PLUS PLUS coding, C++ / CPP / C PLUS PLUS codes, C++ / CPP / C PLUS PLUS slides, C++ / CPP / C PLUS PLUS notes
The document discusses try/catch blocks in Java and how they can be used to handle errors and exceptions. It covers:
1) Using try/catch blocks allows code to fix errors and prevent program termination by handling exceptions.
2) Multiple catch clauses can be specified to handle different exception types thrown from the same code block.
3) Try blocks can be nested, with inner exceptions caught by inner handlers or bubbled up to outer handlers if uncaught.
This document discusses exception handling in C++. It covers try-catch blocks, multiple catch blocks, catch-all blocks, and rethrowing exceptions. Try blocks contain code that may throw exceptions. Catch blocks catch exceptions thrown from try blocks and handle them. Multiple catch blocks allow handling different exception types. Catch-all blocks catch any exception not caught previously. Exceptions can be rethrown using throw to pass handling to outer try-catch blocks.
This document provides an overview of exception handling in Java, including try/catch blocks, checked and unchecked exceptions, custom exceptions, and exception propagation. It defines exceptions as abnormal code conditions, explains how to handle exceptions with try/catch/finally, and covers exception hierarchies, multiple catch blocks, and system-defined vs. programmer-defined exceptions.
The document discusses exception handling and templates in C++. It describes exception handling using try, catch, and throw keywords. It also explains function templates and class templates which allow creating generic functions and classes that can work with different data types.
The document discusses exception handling in Java. It defines different types of errors like logical errors, compilation errors, and runtime errors. It explains checked and unchecked exceptions. It describes how to handle exceptions using try, catch, and finally blocks. It provides examples of handling ArithmeticException and other exceptions. It also discusses multi-catch, throw statement, re-throwing exceptions, and throws keyword to declare exceptions in method signatures.
The document discusses exception handling in C++. It provides examples of throwing exceptions from functions using try/catch blocks. It explains that exceptions allow programs to handle errors and unexpected situations gracefully rather than crashing. The document also discusses catching multiple exception types using multiple catch blocks or a catch-all block. Well-handled exceptions can prevent bugs and make programs more robust.
Similar to Object Oriented Programming Using C++: C++ Exception Handling.pptx (20)
Discover the latest insights on Data Driven Maintenance with our comprehensive webinar presentation. Learn about traditional maintenance challenges, the right approach to utilizing data, and the benefits of adopting a Data Driven Maintenance strategy. Explore real-world examples, industry best practices, and innovative solutions like FMECA and the D3M model. This presentation, led by expert Jules Oudmans, is essential for asset owners looking to optimize their maintenance processes and leverage digital technologies for improved efficiency and performance. Download now to stay ahead in the evolving maintenance landscape.
Open Channel Flow: fluid flow with a free surfaceIndrajeet sahu
Open Channel Flow: This topic focuses on fluid flow with a free surface, such as in rivers, canals, and drainage ditches. Key concepts include the classification of flow types (steady vs. unsteady, uniform vs. non-uniform), hydraulic radius, flow resistance, Manning's equation, critical flow conditions, and energy and momentum principles. It also covers flow measurement techniques, gradually varied flow analysis, and the design of open channels. Understanding these principles is vital for effective water resource management and engineering applications.
Home security is of paramount importance in today's world, where we rely more on technology, home
security is crucial. Using technology to make homes safer and easier to control from anywhere is
important. Home security is important for the occupant’s safety. In this paper, we came up with a low cost,
AI based model home security system. The system has a user-friendly interface, allowing users to start
model training and face detection with simple keyboard commands. Our goal is to introduce an innovative
home security system using facial recognition technology. Unlike traditional systems, this system trains
and saves images of friends and family members. The system scans this folder to recognize familiar faces
and provides real-time monitoring. If an unfamiliar face is detected, it promptly sends an email alert,
ensuring a proactive response to potential security threats.
Use PyCharm for remote debugging of WSL on a Windo cf5c162d672e4e58b4dde5d797...shadow0702a
This document serves as a comprehensive step-by-step guide on how to effectively use PyCharm for remote debugging of the Windows Subsystem for Linux (WSL) on a local Windows machine. It meticulously outlines several critical steps in the process, starting with the crucial task of enabling permissions, followed by the installation and configuration of WSL.
The guide then proceeds to explain how to set up the SSH service within the WSL environment, an integral part of the process. Alongside this, it also provides detailed instructions on how to modify the inbound rules of the Windows firewall to facilitate the process, ensuring that there are no connectivity issues that could potentially hinder the debugging process.
The document further emphasizes on the importance of checking the connection between the Windows and WSL environments, providing instructions on how to ensure that the connection is optimal and ready for remote debugging.
It also offers an in-depth guide on how to configure the WSL interpreter and files within the PyCharm environment. This is essential for ensuring that the debugging process is set up correctly and that the program can be run effectively within the WSL terminal.
Additionally, the document provides guidance on how to set up breakpoints for debugging, a fundamental aspect of the debugging process which allows the developer to stop the execution of their code at certain points and inspect their program at those stages.
Finally, the document concludes by providing a link to a reference blog. This blog offers additional information and guidance on configuring the remote Python interpreter in PyCharm, providing the reader with a well-rounded understanding of the process.
Null Bangalore | Pentesters Approach to AWS IAMDivyanshu
#Abstract:
- Learn more about the real-world methods for auditing AWS IAM (Identity and Access Management) as a pentester. So let us proceed with a brief discussion of IAM as well as some typical misconfigurations and their potential exploits in order to reinforce the understanding of IAM security best practices.
- Gain actionable insights into AWS IAM policies and roles, using hands on approach.
#Prerequisites:
- Basic understanding of AWS services and architecture
- Familiarity with cloud security concepts
- Experience using the AWS Management Console or AWS CLI.
- For hands on lab create account on [killercoda.com](https://killercoda.com/cloudsecurity-scenario/)
# Scenario Covered:
- Basics of IAM in AWS
- Implementing IAM Policies with Least Privilege to Manage S3 Bucket
- Objective: Create an S3 bucket with least privilege IAM policy and validate access.
- Steps:
- Create S3 bucket.
- Attach least privilege policy to IAM user.
- Validate access.
- Exploiting IAM PassRole Misconfiguration
-Allows a user to pass a specific IAM role to an AWS service (ec2), typically used for service access delegation. Then exploit PassRole Misconfiguration granting unauthorized access to sensitive resources.
- Objective: Demonstrate how a PassRole misconfiguration can grant unauthorized access.
- Steps:
- Allow user to pass IAM role to EC2.
- Exploit misconfiguration for unauthorized access.
- Access sensitive resources.
- Exploiting IAM AssumeRole Misconfiguration with Overly Permissive Role
- An overly permissive IAM role configuration can lead to privilege escalation by creating a role with administrative privileges and allow a user to assume this role.
- Objective: Show how overly permissive IAM roles can lead to privilege escalation.
- Steps:
- Create role with administrative privileges.
- Allow user to assume the role.
- Perform administrative actions.
- Differentiation between PassRole vs AssumeRole
Try at [killercoda.com](https://killercoda.com/cloudsecurity-scenario/)
Software Engineering and Project Management - Introduction, Modeling Concepts...Prakhyath Rai
Introduction, Modeling Concepts and Class Modeling: What is Object orientation? What is OO development? OO Themes; Evidence for usefulness of OO development; OO modeling history. Modeling
as Design technique: Modeling, abstraction, The Three models. Class Modeling: Object and Class Concept, Link and associations concepts, Generalization and Inheritance, A sample class model, Navigation of class models, and UML diagrams
Building the Analysis Models: Requirement Analysis, Analysis Model Approaches, Data modeling Concepts, Object Oriented Analysis, Scenario-Based Modeling, Flow-Oriented Modeling, class Based Modeling, Creating a Behavioral Model.
Applications of artificial Intelligence in Mechanical Engineering.pdfAtif Razi
Historically, mechanical engineering has relied heavily on human expertise and empirical methods to solve complex problems. With the introduction of computer-aided design (CAD) and finite element analysis (FEA), the field took its first steps towards digitization. These tools allowed engineers to simulate and analyze mechanical systems with greater accuracy and efficiency. However, the sheer volume of data generated by modern engineering systems and the increasing complexity of these systems have necessitated more advanced analytical tools, paving the way for AI.
AI offers the capability to process vast amounts of data, identify patterns, and make predictions with a level of speed and accuracy unattainable by traditional methods. This has profound implications for mechanical engineering, enabling more efficient design processes, predictive maintenance strategies, and optimized manufacturing operations. AI-driven tools can learn from historical data, adapt to new information, and continuously improve their performance, making them invaluable in tackling the multifaceted challenges of modern mechanical engineering.
2. An exception is a problem that arises during the execution of a program.
When executing C++ code, different errors can occur: coding errors made by
the programmer, errors due to wrong input, an attempt to divide by zero or
other unforeseeable things.
Exception handling in C++ consist of three keywords: try, throw and catch:
try − The try statement allows you to define a block of code to be tested for
errors while it is being executed.
throw − A program throws an exception when a problem shows up. This is
done using a throw keyword.
catch − The catch statement allows you to define a block of code to be
executed, if an error occurs in the try block.
Introduction
3. #include <iostream>
#include <stdlib.h>
using namespace std;
int main() {
int x = -1; // Some code
cout << "Before try n";
try {
cout << "Inside try n";
if (x < 0) {
throw x;
cout << "After throw "
<< "(Never executed) n";
}
}
catch (int x) {
cout <<"Exception Caught and x = "
<< x << endl;
}
Example 1: Exception Handling
cout << "After catch "
<< "(Will be executed) n";
system("PAUSE");
return 0;
}
Page 1 Page 2
4. Exceptions can be thrown anywhere within a code block using throw
statement. The operand of the throw statement determines a type for the
exception and can be any expression and the type of the result of the
expression determines the type of exception thrown.
Following is an example of throwing an exception when dividing by zero
condition occurs:
Throwing Exceptions
double division(int a, int b) {
if (b == 0) {
throw "Division by zero condition!";
}
return (a / b);
}
5. #include <iostream>
#include <stdlib.h>
using namespace std;
double division(int a, int b) {
if (b == 0) {
throw "Division by zero condition!";
}
return (a / b);
}
Example 2: Divide by Zero Exception
int main() {
int x = 50, y = 0;
double z = 0;
try {
z = division(x, y);
cout << z << endl;
}
catch (const char* msg) {
cout << msg << endl;
}
system("PAUSE");
return 0;
}
Page 1 Page 2
Because we are raising
(throwing) an exception of type
const char*, so while catching
this exception, we have to use
const char* in catch block.
6. The catch block following the try block catches any exception. You can specify
what type of exception you want to catch and this is determined by the
exception declaration that appears in parentheses following the keyword
catch.
Above code will catch an exception of ExceptionName type. If you want to
specify that a catch block should handle any type of exception that is thrown
in a try block, you must put an ellipsis, ..., between the parentheses enclosing
the exception declaration as follows
Catching Exceptions
try {
// protected code
}
catch (ExceptionName e) {
// code to handle ExceptionName exception
}
7. #include <iostream>
#include <exception>
using namespace std;
int main() {
try {
int age = 15;
if (age >= 18) {
cout << "Access granted - "
<< "you are old enough.";
}
else {
throw (age);
}
}
Example 3: Exception Handling
catch (int myNum) {
cout << "Access denied - "
<< "You must be at least "
<< "18 years old.n";
cout << "Your Age is: " << myNum
<< endl;
}
system("PAUSE");
return 0;
}
Page 1 Page 2
8. We use the try block to test some code: If the age variable is less than 18, we
will throw an exception, and handle it in our catch block.
In the catch block, we catch the error and do something about it. The catch
statement takes a parameter: in our example we use an int variable (myNum)
(because we are throwing an exception of int type in the try block (age)), to
output the value of age.
If no error occurs (e.g. if age is 20 instead of 15, meaning it will be greater
than 18), the catch block is skipped: The catch block following the try block
catches any exception. You can specify what type of exception you want to
catch and this is determined by the exception declaration that appears in
parentheses following the keyword catch.
Example 3 Explained
9. #include <iostream>
#include <exception>
using namespace std;
int main() {
try {
int age = 15;
if (age >= 18) {
cout << "Access granted - "
<< "you are old enough.";
}
else {
throw (501);
}
}
Example 4: Exception Handling Using Error Number
catch (int e) {
cout << "Access deniedn";
cout << "Error Number is: " << e
<< endl;
}
system("PAUSE");
return 0;
}
Page 1 Page 2
You can also use the throw keyword to
output a reference number, like a
custom error number/code for
organizing purposes:
10. There is a special catch block called the ‘catch all’ block, written as catch(…),
that can be used to catch all types of exceptions
If you do not know the throw type used in the try block, you can use the
"three dots" syntax (...) inside the catch block, which will handle any type of
exception
Handle Any Type of Exception
try {
// protected code
throw exception_error
} catch(...) {
// code to handle any exception
}
11. #include <iostream>
#include <exception>
using namespace std;
int main() {
try {
int age = 15;
if (age >= 18) {
cout << "Access granted - "
<< "you are old enough.";
}
else {
throw (age);
}
}
Example 5: Using Catch All Block
catch (double e) {
cout << "Age = " << e << endl;
}
catch (...) {
cout << "Access denied - "
<< "You must be at least "
<< "18 years old.n";
}
system("PAUSE");
return 0;
}
Page 1 Page 2
12. If an exception is thrown and not caught anywhere, the program terminates
abnormally.
For example, in the next program, a char is thrown, but there is no catch block
to catch the char.
Handle Any Type of Exception
13. #include <iostream>
#include <stdlib.h>
using namespace std;
int main() {
try {
throw 'a';
}
catch (int x) {
cout << "Caught " << x << endl;
}
// catch (char c) {
// cout << "Caught " << c << endl;
// }
system("PAUSE");
return 0;
}
Example 6: Ignoing an Exception
Page 1 Page 2
14. #include <iostream>
#include <stdlib.h>
using namespace std;
int main() {
try {
try {
throw 20;
}
catch (int n) {
cout << "n = "<< n
<< " Handle Partially n";
throw; // Re-throwing an exception
}
}
catch (int n) {
cout << "n = "<< n
<< " Handle remaining n";
}
Example 7: Nested try/catch blocks
system("PAUSE");
return 0;
}
Page 1 Page 2
In C++, try/catch blocks can be nested.
Also, an exception can be re-thrown
using “throw”
So a function can handle a part and ask
the caller to handle the remaining.
15. You can define your own exceptions by inheriting and overriding exception
class functionality. Following is the example, which shows how you can use
std::exception class to implement your own exception in standard way −
In the next code, what() is a public method provided by exception class and
it has been overridden by all the child exception classes. This returns the cause
of an exception.
Defining New Exceptions
16. #include <iostream>
#include <exception>
using namespace std;
struct MyException : public exception {
const char * what () const throw () {
return "C++ Exception";
}
};
Example 8: Defining New Exceptions
int main() {
try {
throw MyException();
} catch(MyException& e) {
std::cout << "MyException caught"
<< std::endl;
std::cout << e.what()
<< std::endl;
} catch(std::exception& e) {
// Other errors
}
}
Page 1 Page 2
17. #include <iostream>
using namespace std;
const int MAX = 3; // stack size
class Stack {
private:
int st[MAX]; int top;
public:
class Exception_Full { };
class Exception_Empty { };
Stack() { top = -1; }
void push(int var) {
if (top >= MAX - 1) //if stack full,
throw Exception_Full();
st[++top] = var;
}
int pop() { // take number off stack
if (top < 0) //if stack empty,
throw Exception_Empty();
return st[top--];
}
Example 9: Using Exception Class
};
int main() {
Stack s1;
try {
s1.push(11); s1.push(22);
s1.push(33); // s1.push(44);
cout << s1.pop() << endl;
cout << s1.pop() << endl;
cout << s1.pop() << endl;
cout << s1.pop() << endl;
}
catch (Stack::Exception_Full) {
cout << "Exception: Stack Full" << endl;
}
catch (Stack::Exception_Empty) {
cout << "Exception: Stack Empty" << endl;
}
cout << "I am outside of try / catch "
<< endl; return 0;
}
Page 1 Page 2
18. #include <iostream>
#include <stdlib.h>
using namespace std;
class Distance {
private:
int feet; float inches;
public:
class Inches_Ex { }; //exception class
Distance() { feet = 0; inches = 0.0; }
Distance(int ft, float in) {
if (in >= 12.0) // if inches too big,
throw Inches_Ex(); //throw exception
feet = ft; inches = in;
}
void getdist() {
cout << "Enter feet : "; cin >> feet;
cout << " inches : "; cin >> inches;
if (inches >= 12.0)
throw Inches_Ex(); //throw exception
}
Example 10: Exceptions with the Distance Class
void showdist(){
cout << feet << "' - " << inches << ""n";
}
};
int main() {
try {
Distance dist1(17, 3.5); //2-arg constructor
Distance dist2; // no-arg constructor
dist2.getdist(); //get distance from user
cout << "dist1 = "; dist1.showdist();
cout << "dist2 = "; dist2.showdist();
}
catch (Distance::Inches_Ex) {
cout << "Initialization error : "
<< "inches value is too large."<<endl;
}
system("pause");
return 0;
}
1 Page 2
19. #include <iostream>
#include <stdlib.h>
#include <string>
using namespace std;
class Inches_Ex { // exception class
public:
string origin; // for name of routine
float iValue; // for inches value
Inches_Ex(string str, float in) {
origin = str; // store string
iValue = in; // store inches
}
}; // end of exception class
Example 11: Exception with arguments
class Distance {
private:
int feet; float inches;
public:
Distance() { feet = 0; inches = 0.0; }
Distance(int ft, float in) {
if (in >= 12.0) // if inches too big,
throw Inches_Ex("2 - arg constructor", in);
feet = ft; inches = in;
}
void getdist() {
cout << "Enter feet : "; cin >> feet;
cout << " inches : "; cin >> inches;
if (inches >= 12.0)
throw Inches_Ex("in getdist()", inches);
}
void showdist() {
cout << feet << "' - " << inches << ""n";
}
};
P1 Page 2
20. int main() {
try {
Distance dist1(17, 3.5);
Distance dist2; // no-arg constructor
dist2.getdist();
cout << "dist1 = "; dist1.showdist();
cout << "dist2 = "; dist2.showdist();
}
catch (Inches_Ex e) {
cout << "Initialization error in " << e.origin << endl
<< "Inches value of " << e.iValue << " is too large." << endl;
}
system("pause");
return 0;
}
Example 12: Exception with arguments
Page 3