c ++异常处理_C ++中的异常处理

c ++异常处理

Errors can be broadly categorized into two types. We will discuss them one by one.

错误可以大致分为两种类型。 我们将一一讨论。

  1. Compile Time Errors

    编译时错误

  2. Run Time Errors

    运行时错误

Compile Time Errors – Errors caught during compiled time is called Compile time errors. Compile time errors include library reference, syntax error or incorrect class import.

编译时错误编译时捕获的错误称为编译时错误。 编译时错误包括库引用,语法错误或不正确的类导入。

Run Time Errors - They are also known as exceptions. An exception caught during run time creates serious issues.

运行时错误 -它们也称为异常。 运行时捕获的异常会导致严重的问题。

Errors hinder normal execution of program. Exception handling is the process of handling errors and exceptions in such a way that they do not hinder normal execution of the system. For example, User divides a number by zero, this will compile successfully but an exception or run time error will occur due to which our applications will be crashed. In order to avoid this we'll introduce exception handling technics in our code.

错误会阻碍程序的正常执行。 异常处理是以不妨碍系统正常执行的方式处理错误和异常的过程。 例如,用户将一个数字除以零,这将成功编译,但是将发生异常或运行时错误,导致我们的应用程序崩溃。 为了避免这种情况,我们将在代码中引入异常处理技术。

In C++, Error handling is done using three keywords:

在C ++中,使用三个关键字来完成错误处理:

  • try

    尝试

  • catch

    抓住

  • throw

Syntax:

句法:

try
{
    //code
    throw parameter;
}
catch(exceptionname ex)
{
    //code to handle exception
}

try阻止 (try block)

The code which can throw any exception is kept inside(or enclosed in) atry block. Then, when the code will lead to any error, that error/exception will get caught inside the catch block.

可能引发任何异常的代码保存在try块内(或包含在try块中)。 然后,当代码将导致任何错误时,该错误/异常将被捕获在catch块内。

catch(catch block)

catch block is intended to catch the error and handle the exception condition. We can have multiple catch blocks to handle different types of exception and perform different actions when the exceptions occur. For example, we can display descriptive messages to explain why any particular excpetion occured.

catch块旨在捕获错误并处理异常情况。 我们可以有多个catch块来处理不同类型的异常,并在发生异常时执行不同的操作。 例如,我们可以显示描述性消息来解释为什么发生任何特定的排他性行为。

throw声明 (throw statement)

It is used to throw exceptions to exception handler i.e. it is used to communicate information about error. A throw expression accepts one parameter and that parameter is passed to handler.

它用于向异常处理程序抛出异常,即,用于传达有关错误的信息。 throw表达式接受一个参数,并将该参数传递给处理程序。

throw statement is used when we explicitly want an exception to occur, then we can use throw statement to throw or generate that exception.

throw当我们明确地要发生异常语句中使用,那么我们可以用throw声明抛出或生成异常。

了解异常处理的需求 (Understanding Need of Exception Handling)

Let's take a simple example to understand the usage of try, catch and throw.

让我们举一个简单的例子来了解try,catch和throw的用法。

Below program compiles successfully but the program fails at runtime, leading to an exception.

下面的程序成功编译,但程序在运行时失败,导致异常。

#include <iostream>#include<conio.h>
using namespace std;
int main()
{
    int a=10,b=0,c;
    c=a/b;
    return 0;
}

The above program will not run, and will show runtime error on screen, because we are trying to divide a number with 0, which is not possible.

上面的程序将无法运行,并且会在屏幕上显示运行时错误 ,因为我们试图将数字除以0 ,这是不可能的。

How to handle this situation? We can handle such situations using exception handling and can inform the user that you cannot divide a number by zero, by displaying a message.

如何处理这种情况? 我们可以使用异常处理来处理此类情况,并且可以通过显示消息来通知用户您不能将数字除以零。

使用trycatchthrow语句 (Using try, catch and throw Statement)

Now we will update the above program and include exception handling in it.

现在,我们将更新上述程序,并在其中包括异常处理。

#include <iostream>
#include<conio.h>
using namespace std;
int main()
{
    int a=10, b=0, c;
    // try block activates exception handling
    try 
    {
        if(b == 0)
        {
            // throw custom exception
            throw "Division by zero not possible";
            c = a/b;
        }
    }
    catch(char* ex) // catches exception
    {
        cout<<ex;
    }
    return 0;
}

Division by zero not possible

不可能被零除

In the code above, we are checking the divisor, if it is zero, we are throwing an exception message, then the catch block catches that exception and prints the message.

在上面的代码中,我们正在检查除数,如果除数为零,则抛出异常消息,然后catch块捕获该异常并打印该消息。

Doing so, the user will never know that our program failed at runtime, he/she will only see the message "Division by zero not possible".

这样做,用户将永远不会知道我们的程序在运行时失败,他/她将仅看到消息“不可能除以零”。

This is gracefully handling the exception condition which is why exception handling is used.

这是在优雅地处理异常情况,这就是使用异常处理的原因。

使用多个catch(Using Multiple catch blocks)

Below program contains multiple catch blocks to handle different types of exception in different way.

下面的程序包含多个catch块,以不同的方式处理不同类型的异常。

#include <iostream>
#include<conio.h>
using namespace std;

int main()
{
    int x[3] = {-1,2};
    for(int i=0; i<2; i++)
    {
        int ex = x[i];
        try 
        {
            if (ex > 0)
                // throwing numeric value as exception
                throw ex;
            else
                // throwing a character as exception
                throw 'ex';
        } 
        catch (int ex)  // to catch numeric exceptions
        {
            cout << "Integer exception\n";
        } 
        catch (char ex) // to catch character/string exceptions
        {
            cout << "Character exception\n";
        }
    }
}

Integer exception Character exception

整数异常字符异常

The above program is self-explanatory, if the value of integer in the array x is less than 0, we are throwing a numeric value as exception and if the value is greater than 0, then we are throwing a character value as exception. And we have two different catch blocks to catch those exceptions.

上面的程序是不言自明的,如果数组x的整数值小于0,则抛出数字值作为异常,如果值大于0,则抛出字符值作为异常。 我们有两个不同的catch块来捕获那些异常。

C ++中的通用catch(Generalized catch block in C++)

Below program contains a generalized catch block to catch any uncaught errors/exceptions. catch(...) block takes care of all type of exceptions.

下面的程序包含一个通用的catch块,用于捕获任何未捕获的错误/异常。 catch(...)块处理所有类型的异常。

#include <iostream>
#include<conio.h>
using namespace std;

int main()
{
    int x[3] = {-1,2};
    for(int i=0; i<2; i++)
    {
        int ex=x[i];
        try 
        {
            if (ex > 0)
                throw ex;
            else
                throw 'ex';
        } 
        // generalised catch block
        catch (...) 
        {
            cout << "Special exception\n";
        }
    }
return 0;
}

Special exception Special exception

特殊例外特殊例外

In the case above, both the exceptions are being catched by a single catch block. We can even have separate catch blocks to handle integer and character exception along with th generalised catch block.

在上述情况下,两个异常都被单个catchcatch 。 我们甚至可以有单独的catch块以及广义的catch块来处理整数和字符异常。

C ++中的标准异常 (Standard Exceptions in C++)

There are some standard exceptions in C++ under <exception> which we can use in our programs. They are arranged in a parent-child class hierarchy which is depicted below:

C ++中的<exception>下有一些标准异常,我们可以在程序中使用它们。 它们按父子类层次结构排列,如下所示:

  • std::exception - Parent class of all the standard C++ exceptions.

    std :: exception-所有标准C ++异常的父类。

  • logic_error - Exception happens in the internal logical of a program.

    逻辑错误 -程序内部逻辑中发生异常。

    • domain_error - Exception due to use of invalid domain.domain_error-由于使用无效域而导致的异常。
    • invalid argument - Exception due to invalid argument.无效的参数 -由于无效的参数而导致的异常。
    • out_of_range - Exception due to out of range i.e. size requirement exceeds allocation.out_of_range-由于超出范围,即大小要求超出分配范围而导致的异常。
    • length_error - Exception due to length error.length_error-由于长度错误而导致的异常。
  • runtime_error - Exception happens during runtime.

    runtime_error-运行时发生异常。

    • range_error - Exception due to range errors in internal computations.range_error-由于内部计算中的范围错误而引起的异常。
    • overflow_error - Exception due to arithmetic overflow errors.overflow_error-由于算术溢出错误而导致的异常。
    • underflow_error - Exception due to arithmetic underflow errorsunderflow_error-由于算术下溢错误而导致的异常
  • bad_alloc - Exception happens when memory allocation with new() fails.

    bad_alloc-当使用new()进行内存分配失败时,发生异常。

  • bad_cast - Exception happens when dynamic cast fails.

    bad_cast-动态转换失败时发生异常。

  • bad_exception - Exception is specially designed to be listed in the dynamic-exception-specifier.

    bad_exception-异常是专门为在dynamic-exception-specifier中列出而设计的。

  • bad_typeid - Exception thrown by typeid.

    bad_typeid -typeid引发的异常。

翻译自: https://www.studytonight.com/cpp/exception-handling-in-cpp.php

c ++异常处理

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值