In python, why not use, with the exception of:

In python, is it true that except Exception as exor except BaseException as exmatches except:, but you get an exception link?

From what I understand, BaseExceptionthis is the new default catch-all.

In addition, why do you need only an offer except:?

+4
source share
5 answers

There are several differences besides Pokémon * exception handling - a bad idea .

Neither except Exception:will except BaseException:they catch the exceptions of the old-style class (Python 2 only):

>>> class Foo(): pass
... 
>>> try:
...     raise Foo()
... except Exception:
...     print 'Caught'
... 
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
__main__.Foo: <__main__.Foo instance at 0x10ef566c8>
>>> try:
...     raise Foo()
... except BaseException:
...     print 'Caught'
... 
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
__main__.Foo: <__main__.Foo instance at 0x10ef56680>
>>> try:
...     raise Foo()
... except:
...     print 'Caught'
... 
Caught

BaseException Exception. , Exception, .

, BaseException, Exception; . SystemExit, KeyboardInterrupt GeneratorExit , . except BaseException:, , except Exception .


* Pokémon, .

+4

, , except:. , , , , - . , .

+3

:

  • except , , KeyboardInterrupt;
  • except Exception[ as ex] Exception, , ;
  • except BaseException[ as ex] , except, .

, 2. ( , , , / ), , , . , as ex 2. 3. .

" " .

+3

, .

Python ( ), , . raw , :, , KeyboardInterrupt, ; , BaseException , BaseException, exp:, .

, , Exception, exp:, , , , KeyboardInterrupt.

, , , , ; , , , , , . , (.. , ), pass; , , !

+2

, except:?

: .

The longer answer: using naked except:eliminates the ability to distinguish between exceptions, and even getting a hand on the exception object is a bit more complicated. Thus, you usually always use a form except ExceptionType as e:.

0
source

Source: https://habr.com/ru/post/1531787/


All Articles