Programing

예외를 올바르게 무시하는 방법

lottogame 2020. 9. 30. 08:36
반응형

예외를 올바르게 무시하는 방법


예외를 처리하지 않고 try-except를 수행하려는 경우 Python에서 어떻게 수행합니까?

다음은 올바른 방법입니까?

try:
    shutil.rmtree(path)
except:
    pass

try:
  doSomething()
except: 
  pass

또는

try:
  doSomething()
except Exception: 
  pass

차이점은 첫 번째도 잡을 것입니다 KeyboardInterrupt, SystemExit에서 직접 파생 된 것을, 같은 물건 exceptions.BaseException하지 exceptions.Exception.
자세한 내용은 설명서를 참조하십시오.


일반적으로 관심있는 오류 만 포착하는 것이 모범 사례로 간주됩니다.이 경우 다음과 shutil.rmtree같습니다 OSError.

>>> shutil.rmtree("/fake/dir")
Traceback (most recent call last):
    [...]
OSError: [Errno 2] No such file or directory: '/fake/dir'

이 오류를 조용히 무시하려면 다음을 수행하십시오.

try:
    shutil.rmtree(path)
except OSError:
    pass

왜? (어쨌든) 실수로 문자열 대신 정수를 함수에 전달했다고 가정합니다.

shutil.rmtree(2)

"TypeError : coercing to Unicode : need string or buffer, int found" 라는 오류가 발생 합니다. 디버그하기 어려울 수있는 무시하고 싶지 않을 것입니다.

모든 오류 확실히 무시하고 싶다면 Exception, 맨 except:성명 보다는 catch를 사용 하세요. 다시, 왜?

예외를 지정하지 않으면 예를 들어 다음을 사용 하는 예외를 포함하여 모든 예외가 포착 됩니다 .SystemExitsys.exit()

>>> try:
...     sys.exit(1)
... except:
...     pass
... 
>>>

이를 올바르게 종료하는 다음과 비교하십시오.

>>> try:
...     sys.exit(1)
... except Exception:
...     pass
... 
shell:~$ 

더 잘 작동하는 코드를 작성하려면 OSError예외가 다양한 오류를 나타낼 수 있지만 위의 예 Errno 2에서는 무시하고 싶을 뿐이 므로 더 구체적 일 수 있습니다.

try:
    shutil.rmtree(path)
except OSError, e:
    if e.errno == 2:
        # suppress "No such file or directory" error
        pass
    else:
        # reraise the exception, as it's an unexpected error
        raise

당신은 또한 수 import errno와는 변경 ifif e.errno == errno.ENOENT:


예외를 처리하지 않고 try catch를 수행하고 싶을 때 Python에서 어떻게 수행합니까?

"취급"이 의미하는 바에 따라 다릅니다.

아무 조치도 취하지 않고 잡으려는 경우 게시 한 코드가 작동합니다.

예외가 스택 위로 올라가는 것을 막지 않고 예외에 대해 조치를 취하려는 경우 다음과 같은 것이 필요합니다.

try:
    do_something()
except:
    handle_exception()
    raise  #re-raise the exact same exception that was thrown

먼저이 스레드 에서 Jack o'Connor의 답변을 인용합니다 . 참조 된 스레드가 닫혀서 여기에 씁니다.

"Python 3.4에서이 작업을 수행하는 새로운 방법이 있습니다.

from contextlib import suppress

with suppress(Exception):
    # your code

추가 한 커밋은 다음과 같습니다. http://hg.python.org/cpython/rev/406b47c64480

그리고 여기 저자 Raymond Hettinger가 이것과 다른 온갖 파이썬 매력에 대해 이야기하고 있습니다 : https://youtu.be/OSGv2VnC0go?t=43m23s

이것에 대한 추가 사항은 Python 2.7에 해당합니다.

from contextlib import contextmanager

@contextmanager
def ignored(*exceptions):
    try:
        yield
    except exceptions:
        pass

그런 다음 Python 3.4에서와 같이 사용합니다.

with ignored(Exception):
    # your code

완전성을 위해 :

>>> def divide(x, y):
...     try:
...         result = x / y
...     except ZeroDivisionError:
...         print "division by zero!"
...     else:
...         print "result is", result
...     finally:
...         print "executing finally clause"

... python 튜토리얼에서 .

또한 다음과 같이 예외를 캡처 할 수 있습니다.

>>> try:
...     this_fails()
... except ZeroDivisionError as detail:
...     print 'Handling run-time error:', detail

예외를 올바르게 무시하는 방법은 무엇입니까?

이를 수행하는 방법에는 여러 가지가 있습니다.

그러나 예제 선택에는 일반적인 경우를 다루지 않는 간단한 솔루션이 있습니다.

다음 예에만 해당됩니다.

대신에

try:
    shutil.rmtree(path)
except:
    pass

이 작업을 수행:

shutil.rmtree(path, ignore_errors=True)

This is an argument specific to shutil.rmtree. You can see the help on it by doing the following, and you'll see it can also allow for functionality on errors as well.

>>> import shutil
>>> help(shutil.rmtree)

Since this only covers the narrow case of the example, I'll further demonstrate how to handle this if those keyword arguments didn't exist.

General approach

Since the above only covers the narrow case of the example, I'll further demonstrate how to handle this if those keyword arguments didn't exist.

New in Python 3.4:

You can import the suppress context manager:

from contextlib import suppress

But only suppress the most specific exception:

with suppress(FileNotFoundError):
    shutil.rmtree(path)

You will silently ignore a FileNotFoundError:

>>> with suppress(FileNotFoundError):
...     shutil.rmtree('bajkjbkdlsjfljsf')
... 
>>> 

From the docs:

As with any other mechanism that completely suppresses exceptions, this context manager should be used only to cover very specific errors where silently continuing with program execution is known to be the right thing to do.

Note that suppress and FileNotFoundError are only available in Python 3.

If you want your code to work in Python 2 as well, see the next section:

Python 2 & 3:

When you just want to do a try/except without handling the exception, how do you do it in Python?

Is the following the right way to do it?

try :
    shutil.rmtree ( path )
except :
    pass

For Python 2 compatible code, pass is the correct way to have a statement that's a no-op. But when you do a bare except:, that's the same as doing except BaseException: which includes GeneratorExit, KeyboardInterrupt, and SystemExit, and in general, you don't want to catch those things.

In fact, you should be as specific in naming the exception as you can.

Here's part of the Python (2) exception hierarchy, and as you can see, if you catch more general Exceptions, you can hide problems you did not expect:

BaseException
 +-- SystemExit
 +-- KeyboardInterrupt
 +-- GeneratorExit
 +-- Exception
      +-- StopIteration
      +-- StandardError
      |    +-- BufferError
      |    +-- ArithmeticError
      |    |    +-- FloatingPointError
      |    |    +-- OverflowError
      |    |    +-- ZeroDivisionError
      |    +-- AssertionError
      |    +-- AttributeError
      |    +-- EnvironmentError
      |    |    +-- IOError
      |    |    +-- OSError
      |    |         +-- WindowsError (Windows)
      |    |         +-- VMSError (VMS)
      |    +-- EOFError
... and so on

You probably want to catch an OSError here, and maybe the exception you don't care about is if there is no directory.

We can get that specific error number from the errno library, and reraise if we don't have that:

import errno

try:
    shutil.rmtree(path)
except OSError as error:
    if error.errno == errno.ENOENT: # no such file or directory
        pass
    else: # we had an OSError we didn't expect, so reraise it
        raise 

Note, a bare raise raises the original exception, which is probably what you want in this case. Written more concisely, as we don't really need to explicitly pass with code in the exception handling:

try:
    shutil.rmtree(path)
except OSError as error:
    if error.errno != errno.ENOENT: # no such file or directory
        raise 

When you just want to do a try catch without handling the exception, how do you do it in Python?

This will help you to print what the exception is:( i.e. try catch without handling the exception and print the exception.)

import sys
try:
    doSomething()
except:
    print "Unexpected error:", sys.exc_info()[0]

try:
      doSomething()
except Exception: 
    pass
else:
      stuffDoneIf()
      TryClauseSucceeds()

FYI the else clause can go after all exceptions and will only be run if the code in the try doesn't cause an exception.


In Python, we handle exceptions similar to other language, but the difference is some syntax difference, for example,

try:
    #Your code in which exception can occur
except <here we can put in a particular exception name>:
    # We can call that exception here also, like ZeroDivisionError()
    # now your code
# We can put in a finally block also
finally:
    # Your code...

I needed to ignore errors in multiple commands and fuckit did the trick

import fuckit

@fuckit
def helper():
    print('before')
    1/0
    print('after1')
    1/0
    print('after2')

helper()

Simply raise the relevant exception, just like this:

try:
     raise NameError('Joan')
 except NameError:
     print 'An exception just raised again by Joan!'
     raise

As simple as that. :)

For more details, do read this documentation: https://docs.python.org/3.6/tutorial/errors.html

참고URL : https://stackoverflow.com/questions/730764/how-to-properly-ignore-exceptions

반응형