方法定义或调用中的异常处理? [英] Exception handling in method definition or call?

查看:138
本文介绍了方法定义或调用中的异常处理?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有正确的地方来处理异常。
我应该在我的方法内处理它还是应该在方法调用处理它?或者是否重要?



我很抱歉,但我找不到任何关于这个(谷歌搜索异常处理范围)没有返回我是



示例:

  //这样。 .. 
void readFile(string file)
{
try
{
/ *做我的东西* /
}
catch(异常例外)
{
/ *句柄异常* /
}
}

int main()
{
readFile文件);
}

//还是这样?
void readFile(string file)
{
/ *做我的东西* /
}

int main()
{
try
{
readFile(file);
}
catch(异常异常)
{
/ *句柄异常* /
}
}

提前感谢

解决方案

想要处理这样做有意义的错误。



如果您在上面的示例中想要尝试读取一个文件,如果失败,则可以读取默认文件,您可以像第一个示例一样处理它。 p>

如果readFile操作失败对main()的其余部分至关重要,那么您需要将异常传递给它,因此可以处理对于readFile()的任何影响,当然,你可以随时处理该方法中的错误(或一些可能的异常)并重新抛出或让一些通过或者其他任何东西。



虽然它的程序流确定了异常处理的位置。处理例外,这样做是有道理的。


I was wondering if there is a right place to handle exceptions. Should I handle it inside my method or should I handle it at the method call? Or does it matter at all?

I'm sorry, but I couldn't find anything about this (googling "exception handling scope" didn't returned what I was looking for).

Example:

// this way...
void readFile(string file)
{
    try
    {
        /* do my stuff */
    }
    catch(Exception exception)
    {
        /* handle exception */
    }
}

int main()
{
    readFile(file);
}

// or this way?
void readFile(string file)
{
    /* do my stuff */
}

int main()
{
    try
    {
        readFile(file);
    }
    catch(Exception exception)
    {
        /* handle exception */
    }
}

Thanks in advance.

解决方案

In general you want to handle the error where it makes sense to do so.

If in your example above you want to try to read a file and if that fails then read a default file the you can handle it as in the first example.

If the readFile operation failing is vital to the rest of main() then you need to have the exception passed up to that so it can deal with whatever fallout is for readFile() failing and this would be as in your second example.

Of course you can always handle the error (or some possible exceptions) inside the method and rethrow or let some pass through or whatever.

Really though its your program flow that determines where your exception handling goes. Handle the exception where it makes sense to do so.

这篇关于方法定义或调用中的异常处理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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