如果在 C# 中的 Catch 块中发生异常会发生什么.在这种情况下,调用者的结果是什么 [英] What happens if an exception occurs in Catch block in C#. Also what would be the caller result in that case

查看:14
本文介绍了如果在 C# 中的 Catch 块中发生异常会发生什么.在这种情况下,调用者的结果是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个面试问题,很简单,但我对答案没有信心.

It was an interview question, quite simple, but I am not confident about the answer.

如果 catch 块中发生异常会怎样?

What happens if an exception occurs in catch block ?

我正在尝试举例说明面试官试图问我的问题,如果我的程序没有编译,请更正我的程序,我对此很陌生.底线是如果在 Catch 中发生异常会发生什么,以及 caller int hat case 的值是什么.

I am trying to give an example small prog of what the interviewer was trying to ask me, please correct my program if it is not compiling, I am really new to this. Bottom line is what happens if an exception occurs in Catch and what will be the value of caller int hat case.

例如,我有以下内容:

double Calculate(int x)
{
    try
    {
        x = x/2;
    }
    catch(Exception ex)
    {
        Console.Writeline("Message: "+ ex.Message);
    }
    finally
    {
      x = 10;
    }
    return x;
}

double myResult = Calculate(x); //x can be any number or 0 for example

现在有两个问题:

  1. 如果 catch 块中发生异常会怎样?还有,怎么解决?(这是面试官问类似问题的简单例子).

  1. What happens if an exception happens in catch block ? Also, how to resolve it ? (This is simple example of what the interviewer was asking a similar question).

如果Calculate(x) 方法发生异常,myResult 会发生什么?在所有情况下它的值是多少?(请举例说明每个案例)

What will happen to myResult if an exception happens in Calculate(x) method ?What will be its value in all cases ? (Please explain every case with an example)

我也想详细解释一下.

非常感谢.

推荐答案

catch 块中抛出的异常的行为与没有它抛出的异常的行为相同 - 它会向上堆栈直到它如果存在,则被捕获在更高级别的 catch 块中.如果您想更改或包装原始异常,这样做很正常;即:

An exception thrown in a catch block will behave the same as an exception thrown without it - it will go up the stack until it is caught in a higher level catch block, if one exists. Doing this is quite normal if you want to change or wrap the original exception; i.e.:

public void MyStartMethod
{
    try
    {
        //do something
        MyBadMethod();
    }
    catch(MySpecialException mse)
    {
        //this is the higher level catch block, specifically catching MySpecialException 
    }
}

public void MyBadMethod()
{
    try
    {
        //do something silly that causes an exception
    }
    catch (Exception e)
    {
        //do some logging

        throw new MySpecialException(e);
    }
}

public class MySpecialException : Exception 
{   
    public MySpecialException(Exception e) { ...etc... }
}

在您的情况下,myResult 将具有它之前的任何值,如果它仍在范围内.

In your case, myResult will have whatever value it had before, if it's even still in scope.

这篇关于如果在 C# 中的 Catch 块中发生异常会发生什么.在这种情况下,调用者的结果是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆