处理异常后需要中断
本文关键字:中断 异常 处理 | 更新日期: 2023-09-27 17:56:52
我用 C# 构建了一个应用程序,在捕获异常后我必须中断。我使用了return
,但它返回到调用该模块的模块并继续执行。应该怎么做?
我的代码如下所示:
class a
{
b bee=new b{};
bee.read(name);
bee.write(name);// don want this to get executed if exception is thrown
}
class b
{
read(string name)
{
try{}
catch
{
//caught;
//what should be put here so that it just stops after dialog
// box is shown without moving to the write method?
}
write(string name) {}
}
}
您的代码示例不正确,但假设您有一个包含此代码的方法:
void M()
{
b bee=new b();
bee.read(name);
bee.write(name);// don want this to get executed if exception is thrown
}
如果是这样,则必须在此方法中捕获异常,而不是在该方法中捕获read
异常。这样:
void M()
{
try {
b bee=new b();
bee.read(name);
bee.write(name);// don want this to get executed if exception is thrown
}
catch(Exception e) {
// Proper error handling
}
}
read
方法中,不应禁止显示异常。要么根本不抓住它们,要么重新抛出它们(或者更好的是,抛出一个新的异常,旧的异常是它的InnerExeption
)。
如果以这种方式处理方法 M 中的异常,则如果 bee.read(name)
中的某处发生异常,则不会执行第 bee.write(name)
行。
让异常冒泡到调用方法:
class A {
public void Method() {
B bee = new B{};
try {
bee.Read(name);
bee.Write(name);
} catch(Exception ex) {
// handle exception if needed
}
}
}
class B {
public void Read(string name) {
try{
...
} catch(Exception ex) {
// handle exception if needed
throw;
}
}
public void Write(string name) {
}
}
注意:如果可能,您应该捕获更具体的异常类,而不是捕获基类 Exception。没有 excpetion 参数的 catch 语法已过时。
你可以这样做,如下所示
class a
{
b bee = new b();
try
{
bee.read(name);
bee.write(name);
}
catch(Exception ex)
{
//handle error here
}
}
class b
{
//These are your method implementations without catching the exceptions in b
read
write
}
如果您在方法中捕获异常,那么您将无法知道该方法的执行状态,而无需挂起方法的某种错误状态。无论是布尔返回还是 b 中可访问的错误代码。
为什么不让 read 方法返回一个对调用方有意义的值? 因此,调用方检查读取的返回值,如果它(例如)为 null,则不会调用写入。或者,读取方法可以返回一个枚举值,该值告诉调用方读取方法退出的条件。
作为另一种选择,调用方可以使用 doNotProceed 方法实现接口,然后将自身传递给 read 方法。异常时,读取调用caller.doNotProceed,在调用者对象中设置一个内部变量,这会告诉它不要继续写入。
你有很多选择
您可以使用 return 语句或重新抛出错误并放置另一个父级尝试捕获,但最好重新构建代码。