Exception handling (Exception Handling) in C ++
An Exception is an issue that occurs during the execution of a program. An Exception in C ++ is a response to an exception situation that occurs while a program is running, such as dividing by zero.
Exception provides a way to pass control from one part of a program to another. Exception Handling in C ++ is built on 3 keywords: try, catch, and throw .
- throw : A program throws an Exception when a problem occurs. This is done using the throw keyword in C ++.
- catch : A program catches an Exception with an Exception Handler in place in a program where you want to handle that problem. C ++ catch keyword leads to catching an exception.
- try : A try block can be captured by a specific number of exceptions. It is followed by one or more catch blocks.
Suppose a block will create an Exeption, a method of catching an exception by using a combination of try and catch keywords. A try / catch block is placed around the code that can create an exception. The code inside a try / catch block is treated as protected code, and the syntax to use try / catch in C ++ is as follows:
try { // phan code duoc bao ve } catch ( ten_Exception e1 ) { // day la khoi catch } catch ( ten_Exception e2 ) { // day la khoi catch } catch ( ten_Exception eN ) { // day la khoi catch }
You can list many catch commands to catch different exception types in case your try block appears more than one exception in different situations.
Throw Exception in C ++
Exception can be thrown anywhere within a code block using C ++ throw commands. The command of the throw command determines the type of exception and can be any expression and the type of the result of the expression determines the type of exception thrown.
The following example illustrates throwing an exception when divided by zero in C ++:
double phepchia ( int a , int b ) { if ( b == 0 ) { throw "Chu y: Ban dang chi cho so 0!!!" ; } return ( a / b ); }
Getting Exception in C ++
The catch block following the try block in C ++ will catch any exception. You can determine the type of exception you want to catch and this is determined by the exception declaration that appears in parentheses following the catch keyword in C ++.
try { // phan code duoc bao ve } catch ( ten_Exception e ) { // phan code de xu ly ngoai le co ten la ten_Exception }
The above code will catch an exception of type ten_Exception . If you want to determine that a catch candle block handles any type of exception thrown in a try block, you must place a dot (.) in parentheses following the catch keyword, as follows:
try { // phan code duoc bao ve } catch (.) { // phan code de xu ly bat ky kieu ngoai le nao }
The following example throws an exception when divided by zero and we catch it in the catch block.
#include using namespace std ; double phepchia ( int a , int b ) { if ( b == 0 ) { throw "Chu y: Ban dang chi cho so 0!!!" ; } return ( a / b ); } int main () { int x = 15 ; int y = 0 ; double z = 0 ; try { z = phepchia ( x , y ); cout << z << endl ; } catch ( const char * msg ) { cerr << msg << endl ; } return 0 ; }
Because we're creating an exception of type const char * , so while catching this exception, we have to use const char * in the catch block. Compiling and running the above C ++ program will produce the following results:
Chu y : Ban dang chi cho so 0 !!!
Standard Exception in C ++
C ++ provides a list of defined Standard Exception that we can use in programs. These exceptions are arranged in the parent-child structure as follows:
The following table is a brief description of each exception mentioned in the diagram above:
Exception Description std :: exception An exception and parent of all Standard Exception in C ++ std :: bad_alloc Can be thrown by new std :: bad_cast Can be thrown by dynamic_cast std :: bad_exception This is a useful device to handle Unexpected Exception logic in a C ++ program std :: bad_typeid Can be thrown by typeid std :: logic_error An exception that can theoretically be detected by reading the std :: domain_error code This is an exception thrown when a domain invalid math used std :: invalid_argument Thrown by invalid parameters std :: length_error Thrown when a std :: string is too large to be created std :: out_of_range Can be thrown by a method , for example std :: vector and std :: bitset <> :: operator [] (). std :: runtime_error An exception that cannot theoretically be detected by reading std :: overflow_error code Is thrown if a mathematical overflow occurs std :: range_error Appears when you try to save an external value of the range of std :: underflow_error is thrown if a mathematical underflow appearsDefining new Exception in C ++
You can define exceptions for yourself by inheriting and overwriting the exception class feature in C ++. The following example illustrates how you can use the std :: exception class to deploy your own exception in a standard way in C ++:
#include #include using namespace std ; struct MyException : public exception { const char * what () const throw () { return "Exception trong C++" ; } }; int main () { try { throw MyException (); } catch ( MyException & e ) { std :: cout << "MyException da duoc bat!" << std :: endl ; std :: cout << e . what () << std :: endl ; } catch ( std :: exception & e ) { // phan nay danh cho cac error khac } }
It will produce the following result:
MyException da duoc bat ! Exception trong C ++
Here, what () is a public method provided by the exception class in C ++ and it has been overwritten by all exception subclasses. This example returns the cause of an exception in C ++.
According to Tutorialspoint
Previous article: Read / write File in C ++ | fstream in c ++
Next article: Dynamic memory in C / C ++
You should read it
- Exception handling and error (Error & Exception Handling)
- How to use the Nest.js exception filter for error handling
- How to fix Unhandled Exception Has Occurred errors on Windows 10
- Error and Exception in Python
- How to fix Unexpected Store Exception error in Windows 10
- How to fix 0x0000001E: KMODE EXCEPTION NOT HANDLED on Windows
- Instructions for fixing System Service Exception error on Windows
- Fix 'System Thread Exception Not Handled' error on Windows 10
May be interested
- Error and Exception in Pythonpython often produces exceptions when an error occurs during execution. quantum will work with you to learn about the different exceptions built into this language.
- How to fix 0x0000001E: KMODE EXCEPTION NOT HANDLED on Windowserror 0x0000001e: kmode exception not handled system error handler message cannot handle exceptions generated from kernel mode program.
- Multiple choice quiz about Python - Part 3today's topic quantrimang wants to challenge you is about file and exception handling in python. let's try the following 15 questions!
- Steps to fix 'System Thread Exception Not Handled' errorthere are many causes of 'system thread exception not handled' error on windows 10 and there is no specific cause.
- Handling errors in Cprogramming languages such as c language do not provide direct support for error handling but because they are system program languages, it provides the lowest level of return values. most functions of c and functions in unix return values 1 or null in any error case and set an errno error code for global variables and instructions for errors that occur during the function call.
- Burning with water, a more environmentally friendly method of handling corpses than cremationburning with water or alkaline hydrolysis is a form of eco-friendly rest and much less energy-efficient than cremation and burial.
- How to Configure Sendmailthis how to covers the process of configuring email handling after registering a domain. sendmail is the unix/linux software that does email handling. it's not a mail user agent (mua) like the email programs you'd recognize. it is just a...
- 9 Quick Note Handling Tips for Apple Notes on Macapple notes has a lot of new features on macos. here are some quick tips for managing apple notes on your mac.
- Different Platforms in Gitgnu / linux and mac os use line-feed (lf), or a new line when line-ending characters while windows uses line-feed combination and carriage-return (lfcr) to signify the ending of the character line ends.
- Fix Error 0x0000001E: KMODE EXCEPTION NOT HANDLED On Windowsyou often get the error message '0x0000001e: kmode exception not handled' so where is the error and how to fix it. let's find out through the following article