Home  >  Article  >  Backend Development  >  C++ exception handling mechanism and code examples

C++ exception handling mechanism and code examples

王林
王林Original
2023-08-21 22:07:441527browse

C exception handling mechanism and code examples

In C programming, the exception handling mechanism is a very important concept, which can help us deal with runtime errors and unexpected situations, making the program more robust and reliable . This article will introduce the exception handling mechanism in C, including exception definition, throwing exceptions, catching exceptions, exception handlers, etc., and provide some code examples to help readers better understand and apply.

1. Definition of exception

During the normal execution of the program, if some unhandled errors or unexpected situations are encountered, an exception will occur. Exceptions can be understood as a protection mechanism for the program, which can provide error information and exit the program gracefully when an error occurs in the program to ensure the safety and reliability of the program.

C defines some standard exception classes, which represent different types of exceptions, such as: std::exception, std::bad_alloc, std::runtime_error, etc. We can also customize exception classes to represent specific exceptions.

2. Throwing exceptions

When an exception occurs in the program, you can use the throw keyword to throw the exception and pass the exception object to the exception handler. Usually, the syntax for throwing an exception is as follows:

throw exceptionType(argument);

Among them, exceptionType is the type of the exception class, and argument is the parameter of the exception object, which can be any type of data.

The following is a simple code example that demonstrates how to throw a standard exception class std::runtime_error and pass an error message as a parameter:

#include <iostream>
#include <stdexcept>

void division(int a, int b){
  if (b == 0){
    throw std::runtime_error("Division by zero");
  }
  std::cout << "Result: " << a/b << std::endl;
}

int main(){
  try{
    division(10, 0);
  }
  catch(std::exception& e){
    std::cout << "Exception caught: " << e.what() << std::endl;
  }
  return 0;
}

In the above code, when the divisor is 0 , the program will throw a std::runtime_error exception and pass an error message string as a parameter. In the main function, we use the try-catch statement to catch this exception and print out the exception error message.

3. Catching exceptions

When the program throws an exception, we need to catch and handle the exception to avoid the program crash. You can use try-catch statements to catch exceptions. The syntax is as follows:

try{
  // 可能抛出异常的代码
}
catch(exceptionType1& e1){
  // 处理类型为exceptionType1的异常
}
catch(exceptionType2& e2){
  // 处理类型为exceptionType2的异常
}
catch(...){
  // 处理所有类型的异常
}

In the try statement block, we can include code that may throw exceptions. When the program throws an exception, it will jump out of the try statement block and enter the corresponding catch statement block for processing based on the matching of the exception type and the catch statement. The last catch statement, catch(...), can handle all types of exceptions, but its use is not recommended because it will lose information about the exception object and is inconvenient for program debugging and maintenance.

The following is a simple code example that demonstrates how to catch a std::runtime_error exception and handle it:

#include <iostream>
#include <stdexcept>

void division(int a, int b){
  if (b == 0){
    throw std::runtime_error("Division by zero");
  }
  std::cout << "Result: " << a/b << std::endl;
}

int main(){
  try{
    division(10, 0);
  }
  catch(std::runtime_error& e){
    std::cout << "Exception caught: " << e.what() << std::endl;
  }
  return 0;
}

In the above code, when the divisor is 0, the program throws an std ::runtime_error exception. In the main function, we use the try-catch statement to catch this exception and print out the exception error message.

4. Exception handler

In addition to the try-catch statement, C also provides a special mechanism to handle uncaught exceptions, called an exception handler. You can use the std::set_terminate() function to register an exception handler and execute the handler code when an uncaught exception occurs in the program. Exception handlers are usually used to handle serious errors, such as insufficient memory, file read and write errors, etc.

The following is a simple code example that demonstrates how to register and use an exception handler:

#include <iostream>
#include <cstdlib>

void myExceptionHandler(){
  std::cout << "Unhandled exception" << std::endl;
  std::exit(1);
}

int main(){
  std::set_terminate(myExceptionHandler);
  int* p = new int[1000000000];
  delete[] p;
  return 0;
}

In the above code, we use the std::set_terminate() function to register an exception handler implement myExceptionHandler and allocate a large memory block in the main function. Due to insufficient memory, the program will throw a std::bad_alloc exception. This exception will be caught by the myExceptionHandler processor, print out an error message and exit the program.

Summary

C The exception handling mechanism is a very important part of the program. It can help us deal with runtime errors and unexpected situations, making the program more robust and reliable. This article introduces exception definitions, throwing exceptions, catching exceptions, exception handlers, etc. in C, and provides some code examples to help readers better understand and apply them. In actual programming, we should use the exception handling mechanism reasonably and avoid abuse and misuse to ensure the efficiency and maintainability of the program.

The above is the detailed content of C++ exception handling mechanism and code examples. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn