代码之家  ›  专栏  ›  技术社区  ›  Greg

Java-如何做Python的尝试,除了其他

  •  39
  • Greg  · 技术社区  · 16 年前

    除了Java,我要如何在Python中进行尝试呢?

    例子:

    try:
       something()
    except SomethingException,err:
       print 'error'
    else:
       print 'succeeded'
    

    我看到有人提到过“试着抓住”这个词,但没有其他的。

    3 回复  |  直到 10 年前
        1
  •  22
  •   Ryan Ische    12 年前

    我并不完全相信我喜欢它,但这相当于Python的其他功能。它消除了将成功代码放在try块末尾时发现的问题。

    bool success = true;
    try {
        something();
    } catch (Exception e) {
        success = false;
        // other exception handling
    }
    if (success) {
        // equivalent of Python else goes here
    }
    
        2
  •  2
  •   jjnguy Julien Chastang    16 年前

    虽然没有内置的方式来做这件事。你可以做一些类似的事情来达到类似的结果。这些评论解释了为什么这不是完全相同的事情。

    如果执行 somethingThatCouldError() 通行证, YAY!! 将被打印。如果有错误, SAD 将被打印。

    try {
        somethingThatCouldError();
        System.out.println("YAY!!");
        // More general, code that needs to be executed in the case of success
    } catch (Exception e) {
        System.out.println("SAD");
        // code for the failure case
    }
    

    这种方式比Python稍微不那么明确。但它也达到了同样的效果。

        3
  •  1
  •   matiascelasco    10 年前

    这个怎么样?

    try {
        something();
    } catch (Exception e) {
        // exception handling
        return;
    }
    // equivalent of Python else goes here
    

    当然,在某些情况下,您希望在try/catch/else之后放入更多的代码,而这个解决方案不适合这样做,但是如果它是您方法中唯一的try/catch块,它就会起作用。