从被叫方法捕获异常 [英] Catching an Exception from a called Method

查看:137
本文介绍了从被叫方法捕获异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我想知道是否可以按顺序从方法中捕获错误阻止它执行通常遵循的方法,就像我无法上班的示例。

  public class MyClass {

public static void main(String [] args){

//此方法捕获异常并停止运行
method01();

//此方法将继续,我不想要
method02();

};

};

我通常会有一个静态int变量,当程序运行时将初始化为0,然后如果一个方法有一个异常,它会增加该int,每个方法只会在int为0时运行。



这个工作,但我只是想知道如果我可以替换

解决方案

你可以尝试:

  try {
method01()
} catch(final Exception e){
// do something
return; ///停止处理退出
}

method01将抛出异常:

  private void method01()throws异常{
// something
}


This is something that's been bugging me for a while with regards to Program Flow.

I wanted to know if it's possible to catch an error from a Method in order to stop it from executing the Method that would normally follow it like the example bellow that I can't get to work.

public class MyClass {

   public static void main(String[] args) {

      // this method catches an exception and stops running
      method01();

      // this method will continue anyway which I don't want
      method02();

   };

};

I would normally have a static int variable that will initialize as 0 when the program is run and then if a method ever catches an exception it will increment that int and each method will only run if the int is 0.

This works but I was just wondering if I could replace the int shindig with exception handling.

解决方案

Can you try:

try {
    method01()
} catch (final Exception e) {
    // do something
    return; ///stop processing exit
}

the method01 will throw Exception:

private void method01() throws Exception {
// something
}

这篇关于从被叫方法捕获异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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