抛出异常后我必须休息吗? [英] Do I have to break after throwing exception?

查看:138
本文介绍了抛出异常后我必须休息吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在C#中编写一个自定义类,如果人们在某些方法中输入错误的输入,我会抛出一个异常。如果抛出异常,抛出后的方法中的任何代码是否仍然被执行?扔掉之后我必须休息一下,还是一直抛出这个方法?

解决方案

当你 throw 一个异常,下一个要执行的代码是任何catch该块覆盖该方法(如果有的话),然后, finally block

  try 
{
Console.WriteLine(Yes1);
throw(new Exception());
Console.WriteLine(No1);

}
catch
{
Console.WriteLine(Yes2);
throw;
Console.WriteLine(No2);
}
finally
{
Console.WriteLine(Yes3);
}

Console.WriteLine(No3);


I'm writing a custom class in C# and I'm throwing a couple exceptions if people give the wrong inputs in some of the methods. If the exception is thrown, will any of the code in the method after the throw still be executed? Do I have to put a break after the throw, or does a throw always quit the method?

When you throw an exception, the next code to get executed is any catch block that covers that throw within the method (if any) then, the finally block (if any). You can have a try, a try-catch, a try-catch-finally or a try-finally. Then, if the exception is not handled, re-thrown by a catch block or not caught at all, control is returned to the caller. For example, you will get "Yes1, Yes2, Yes3" from this code ...

try
{
    Console.WriteLine("Yes1");
    throw (new Exception());
    Console.WriteLine("No1");

}
catch
{
    Console.WriteLine("Yes2");
    throw;
    Console.WriteLine("No2");
}
finally
{
    Console.WriteLine("Yes3");
}

Console.WriteLine("No3");

这篇关于抛出异常后我必须休息吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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