问题描述
这是一个面试问题,很简单,但我没有信心的答案。
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 ?
我想举一个例子小前卫的面试官试图问我,请纠正我的程序,如果它不编译,我真的很新的这一点。底线是,如果在捕捉发生异常,会是怎样的来电INT帽子的情况下,价值会发生什么。
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
现在有两个问题:
-
如果异常在catch块发生,会发生什么?另外,如何解决? (这是一个简单的面试官在问类似的问题的例子)。
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).
会发生什么事,以myResult中如果有异常的计算(x)的方法发生在所有的情况下,什么将是它的价值? (请解释用一个例子任何情况下)
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)
我想有一个详细的解释也明白这一点。
I would like to understand this with a detailed explanation too.
感谢你了。
推荐答案
扔在一个捕捉异常
块的行为一样抛出没有它的异常 - 它会上推,直到它被夹在一个较高的水平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块发生异常会发生什么。此外,这将是主叫结果在这种情况下的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!