具有多个catch块的C#异常处理

In a C# program, we can use multiple catch blocks to handle the multiple exceptions, because sometimes it is also required to handle multiple exceptions of a coding section and obvious a coding section can generate multiple exceptions.

在C#程序中,我们可以使用多个catch块来处理多个异常 ,因为有时还需要处理一个编码节的多个异常,并且显然一个编码节可以生成多个异常。

Consider the below example,

考虑下面的示例,

Here, we are using two catch blocks, one is using to catch "DivideByZeroException" which will occur when any number will be divided by zero and second is using to catch any other exceptions as we have discussed in previous tutorial (C# exception handling) that "Exception" class is a superclass and can be used to handle all type of exceptions.

在这里,我们使用了两个catch块,一个用于捕获“ DivideByZeroException” ,当任何数字被零除时,将发生“ DivideByZeroException” ,第二个用于捕获任何其他异常,如我们在上一教程( C#异常处理 )中所讨论的那样, “异常”类是超类,可用于处理所有类型的异常。

using System;

class Program
{
    static void Main()
    {
        int number1 = 20;
        int number2 = 0;
        int result  = 0;

        try
        {
            result = number1 / number2;
            Console.WriteLine("Result : " + result);
        }
        catch (DivideByZeroException e)
        {
            Console.WriteLine(e.Message);
        }
        catch (Exception)
        {
            Console.WriteLine("Exception Occured");
        }
        
    }
}

Output

输出量

exception handling in C#

在不使用异常类的情况下捕获异常 (Catching the exceptions without using exception classes)

If we don't know about the specific class that should be used to catch the particular exception, then we can also handle/catch the exception by using the "catch" keyword only. There is no need to use the class name, consider the below program in which we are not specifying any exception class.

如果我们不知道应该用于捕获特定异常的特定类,那么我们也可以仅使用“ catch”关键字来处理/捕获异常。 不需要使用类名,请考虑下面的程序,其中我们没有指定任何异常类。

using System;

class Program
{
    static void Main()
    {
       
        int result  = 0;
        int num = 0;

        try
        {
            result = 500 / num;
            Console.WriteLine("This line will not execute");
        }
        catch 
        {
            Console.WriteLine("Exception occurred in try block");
        }
    }
}

Output

输出量

Exception occurred in try block


翻译自: https://www.includehelp.com/dot-net/exception-handling-with-multiple-catch-blocks-csharp.aspx

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值