Функции excepthook() и exc_info() модуля sys в python

Exception hierarchy¶

The class hierarchy for built-in exceptions is:

BaseException
 +-- SystemExit
 +-- KeyboardInterrupt
 +-- GeneratorExit
 +-- Exception
      +-- StopIteration
      +-- StopAsyncIteration
      +-- ArithmeticError
      |    +-- FloatingPointError
      |    +-- OverflowError
      |    +-- ZeroDivisionError
      +-- AssertionError
      +-- AttributeError
      +-- BufferError
      +-- EOFError
      +-- ImportError
      |    +-- ModuleNotFoundError
      +-- LookupError
      |    +-- IndexError
      |    +-- KeyError
      +-- MemoryError
      +-- NameError
      |    +-- UnboundLocalError
      +-- OSError
      |    +-- BlockingIOError
      |    +-- ChildProcessError
      |    +-- ConnectionError
      |    |    +-- BrokenPipeError
      |    |    +-- ConnectionAbortedError
      |    |    +-- ConnectionRefusedError
      |    |    +-- ConnectionResetError
      |    +-- FileExistsError
      |    +-- FileNotFoundError
      |    +-- InterruptedError
      |    +-- IsADirectoryError
      |    +-- NotADirectoryError
      |    +-- PermissionError
      |    +-- ProcessLookupError
      |    +-- TimeoutError
      +-- ReferenceError
      +-- RuntimeError
      |    +-- NotImplementedError
      |    +-- RecursionError
      +-- SyntaxError
      |    +-- IndentationError
      |         +-- TabError
      +-- SystemError
      +-- TypeError
      +-- ValueError
      |    +-- UnicodeError
      |         +-- UnicodeDecodeError
      |         +-- UnicodeEncodeError
      |         +-- UnicodeTranslateError
      +-- Warning
           +-- DeprecationWarning
           +-- PendingDeprecationWarning
           +-- RuntimeWarning
           +-- SyntaxWarning
           +-- UserWarning
           +-- FutureWarning
           +-- ImportWarning
           +-- UnicodeWarning
           +-- BytesWarning
           +-- ResourceWarning

Exceptions versus Syntax Errors

Syntax errors occur when the parser detects an incorrect statement. Observe the following example:

The arrow indicates where the parser ran into the syntax error. In this example, there was one bracket too many. Remove it and run your code again:

This time, you ran into an exception error. This type of error occurs whenever syntactically correct Python code results in an error. The last line of the message indicated what type of exception error you ran into.

Instead of showing the message , Python details what type of exception error was encountered. In this case, it was a . Python comes with various built-in exceptions as well as the possibility to create self-defined exceptions.

Базовая структура обработки исключений

В предыдущем разделе мы продемонстрировали, как возникает исключение и как с этим справиться. В этом разделе мы обсудим базовую структуру кодирования для обработки исключений. Таким образом, базовая структура кода для обработки исключений в Python приведена ниже.

name = 'Imtiaz Abedin'
try:
   # Write the suspicious block of code
   print(name)
except AssertionError:  # Catch a single exception
   # This block will be executed if exception A is caught
   print('AssertionError')
except (EnvironmentError, SyntaxError, NameError) as E:  # catch multiple exception
   # This block will be executed if any of the exception B, C or D is caught
   print(E)
except :
   print('Exception')
   # This block will be executed if any other exception other than A, B, C or D is caught
else:
   # If no exception is caught, this block will be executed
   pass
finally:
   # This block will be executed and it is a must!
   pass

# this line is not related to the try-except block
print('This will be printed.')

Здесь вы можете видеть, что мы используем ключевое слово except в другом стиле. Первое ключевое слово except используется для перехвата только одного исключения, а именно исключения AssertionError.

Однако, как видите, второе ключевое слово except используется для перехвата нескольких исключений.

Если вы используете ключевое слово except без упоминания какого-либо конкретного исключения, оно перехватит любое исключение, созданное программой.

Блок else будет выполнен, если не будет найдено исключение. Наконец, независимо от того, будет ли обнаружено какое-либо исключение, будет выполнен блок finally.

Итак, если вы запустите приведенный выше код, мы получим результат:

Если вы измените name на nameee в приведенном выше коде, вы получите следующий результат:

How to Handle Exceptions with Try-Except?

What is Try-Except Statement?

We use the try-except statement to enable exception handling in Python programs.

Inside the try block, you write the code which can raise an exception.

And the code that handles or catches the exception, we place in the except clause.

Python Exception Handling Syntax

Following is the syntax of a Python try-except-else block.

try:
	You do your operations here;
	......................
except ExceptionI:
	If there is ExceptionI, then execute this block.
except ExceptionII:
	If there is ExceptionII, then execute this block.
	......................
else:
	If there is no exception then execute this block.

Have a look – 30 Python Interview Questions for Beginners.

Here is a checklist for using the Python try statement effectively.

  • A single try statement can have multiple except statements depending on the requirement. In this case, a try block contains statements that can throw different types of exceptions.
  • We can also add a generic except clause which can handle all possible types of exceptions.
  • We can even include an else clause after the except clause. The instructions in the else block will execute if the code in the try block doesn’t raise an exception.

Python Exception Handling Examples

Let’s take a sample code to understand the use of Python try-except.

try:
   fob = open("test", "w")
   fob.write("This is my test file for exception handling!!")
except IOError:
   print "Error: can\'t find the file or read data"
else:
   print "Write operation is performed successfully on the file"
   fob.close()

The above code produces the following output.

>>Write operation is performed successfully on the file.

Let’s take another example in which we are trying to open a file in the READ mode.

We’ll perform a WRITE operation on it. Upon execution, it’ll throw an exception.

try:
   fob = open("test", "r")
   fob.write("It's my test file to verify exception handling in Python!!")
except IOError:
   print "Error: can\'t find the file or read data"
else:
   print "Write operation is performed successfully on the file"

The above code produces the following output.

>>Error: can't find file or read data

Exception hierarchy¶

The class hierarchy for built-in exceptions is:

BaseException
 +-- SystemExit
 +-- KeyboardInterrupt
 +-- GeneratorExit
 +-- Exception
      +-- StopIteration
      +-- StopAsyncIteration
      +-- ArithmeticError
      |    +-- FloatingPointError
      |    +-- OverflowError
      |    +-- ZeroDivisionError
      +-- AssertionError
      +-- AttributeError
      +-- BufferError
      +-- EOFError
      +-- ImportError
      |    +-- ModuleNotFoundError
      +-- LookupError
      |    +-- IndexError
      |    +-- KeyError
      +-- MemoryError
      +-- NameError
      |    +-- UnboundLocalError
      +-- OSError
      |    +-- BlockingIOError
      |    +-- ChildProcessError
      |    +-- ConnectionError
      |    |    +-- BrokenPipeError
      |    |    +-- ConnectionAbortedError
      |    |    +-- ConnectionRefusedError
      |    |    +-- ConnectionResetError
      |    +-- FileExistsError
      |    +-- FileNotFoundError
      |    +-- InterruptedError
      |    +-- IsADirectoryError
      |    +-- NotADirectoryError
      |    +-- PermissionError
      |    +-- ProcessLookupError
      |    +-- TimeoutError
      +-- ReferenceError
      +-- RuntimeError
      |    +-- NotImplementedError
      |    +-- RecursionError
      +-- SyntaxError
      |    +-- IndentationError
      |         +-- TabError
      +-- SystemError
      +-- TypeError
      +-- ValueError
      |    +-- UnicodeError
      |         +-- UnicodeDecodeError
      |         +-- UnicodeEncodeError
      |         +-- UnicodeTranslateError
      +-- Warning
           +-- DeprecationWarning
           +-- PendingDeprecationWarning
           +-- RuntimeWarning
           +-- SyntaxWarning
           +-- UserWarning
           +-- FutureWarning
           +-- ImportWarning
           +-- UnicodeWarning
           +-- BytesWarning
           +-- ResourceWarning

The try-finally Clause

You can use a finally: block along with a try: block. The finally block is a place to put any code that must execute, whether the try-block
raised an exception or not. The syntax of the try-finally statement is this −

try:
   You do your operations here;
   ......................
   Due to any exception, this may be skipped.
finally:
   This would always be executed.
   ......................

You cannot use else clause as well along with a finally clause.

Example

#!/usr/bin/python

try:
   fh = open("testfile", "w")
   fh.write("This is my test file for exception handling!!")
finally:
   print "Error: can\'t find file or read data"

If you do not have permission to open the file in writing mode, then this will produce the following result −

Error: can't find file or read data

Same example can be written more cleanly as follows −

#!/usr/bin/python

try:
   fh = open("testfile", "w")
   try:
      fh.write("This is my test file for exception handling!!")
   finally:
      print "Going to close the file"
      fh.close()
except IOError:
   print "Error: can\'t find file or read data"

When an exception is thrown in the try block, the execution immediately passes to the finally block. After all the statements in the finally block are executed, the exception is raised again and is handled in the except statements if present in the next higher layer of the try-except statement.

User-Defined Exceptions

Python also allows you to create your own exceptions by deriving classes from the standard built-in exceptions.

Here is an example related to RuntimeError. Here, a class is created that is subclassed from RuntimeError. This is useful when you need to display more specific information when an exception is caught.

In the try block, the user-defined exception is raised and caught in the except block. The variable e is used to create an instance of the class Networkerror.

class Networkerror(RuntimeError):
   def __init__(self, arg):
      self.args = arg

So once you defined above class, you can raise the exception as follows −

try:
   raise Networkerror("Bad hostname")
except Networkerror,e:
   print e.args

Previous Page
Print Page

Next Page  

ZeroDivisionError

It is not possible to divide by zero. If we try to do this, a
is raised and the script is interrupted.

Note: The following examples demonstrate how
the exceptions work in Python. It is more straightforward to
ensure that the divisor is not zero rather than catch
.

zero_division.py

#!/usr/bin/env python

# zero_division.py


def input_numbers():

    a = float(input("Enter first number:"))
    b = float(input("Enter second number:"))
    return a, b


x, y = input_numbers()
print(f"{x} / {y} is {x/y}")

In this script, we get two numbers from the console. We divide these two numbers.
If the second number is zero, we get an exception.

Enter first number:3
Enter second number:0
Traceback (most recent call last):
    File "C:/Users/Jano/PycharmProjects/Simple/simple.py", line 14, in <module>
    print(f"{x} / {y} is {x/y}")
ZeroDivisionError: float division by zero

We could handle this in two ways.

zero_division2.py

#!/usr/bin/env python

# zero_division2.py


def input_numbers():

    a = float(input("Enter first number:"))
    b = float(input("Enter second number:"))
    return a, b


x, y = input_numbers()

while True:

    if y != 0:

        print(f"{x} / {y} is {x/y}")
        break

    else:

        print("Cannot divide by zero")
        x, y = input_numbers()

First, we simply check that value is not zero. If the
value is zero, we print a warning message and repeat the input
cycle again. This way we handled the error and the script is not interrupted.

$ ./zero_division2.py
Enter first number:4
Enter second number:0
Cannot divide by zero
Enter first number:5
Enter second number:0
Cannot divide by zero
Enter first number:5
Enter second number:6
5.0 / 6.0 is 0.8333333333333334

The other way is to use exceptions.

zero_division3.py

#!/usr/bin/env python

# zerodivision3.py


def input_numbers():

    a = float(input("Enter first number:"))
    b = float(input("Enter second number:"))
    return a, b


x, y = input_numbers()


try:
    print(f"{x} / {y} is {x/y}")

except ZeroDivisionError:

    print("Cannot divide by zero")
    x, y = input_numbers()

We place the code where we expect an exception after keyword.
The keyword catches the exception if it is raised.
The exception type is specified after the keyword.

except ValueError:
    pass
except (IOError, OSError):
    pass

To handle more exceptions, we can either use more except keywords or place
the exception names inside a tuple.

Перехват исключений в Python

В Python исключения обрабатываются при помощи инструкции .

Критическая операция, которая может вызвать исключение, помещается внутрь блока . А код, при помощи которого это исключение будет обработано, — внутрь блока .

Таким образом, мы можем выбрать набор операций, который мы хотим совершить при перехвате исключения. Вот простой пример.

# Для получения типа исключения импортируем модуль sys
import sys

randomList = 

for entry in randomList:
    try:
        print("The entry is", entry)
        r = 1/int(entry)
        break
    except:
        print("Oops!", sys.exc_info(), "occurred.")
        print("Next entry.")
        print()
print("The reciprocal of", entry, "is", r)

Результат:

В данном примере мы, при помощи цикла , производим итерацию списка . Как мы ранее заметили, часть кода, в которой может произойти ошибка, помещена внутри блока .

Если исключений не возникает, блок пропускается, а программа продолжает выполнятся обычным образом (в данном примере так происходит с последним элементом списка). Но если исключение появляется, оно сразу обрабатывается в блоке (в данном примере так происходит с первым и вторым элементом списка).

В нашем примере мы вывели на экран имя исключения при помощи функции , которую импортировали из модуля . Можно заметить, что элемент вызывает , а  вызывает .

Так как все исключения в Python наследуются из базового класса , мы можем переписать наш код следующим образом:

# Для получения типа исключения импортируем модуль sys
import sys

randomList = 

for entry in randomList:
    try:
        print("The entry is", entry)
        r = 1/int(entry)
        break
    except Exception as e:
        print("Oops!", e.__class__, "occurred.")
        print("Next entry.")
        print()
print("The reciprocal of", entry, "is", r)

Результат выполнения этого кода будет точно таким же.

8.4. Raising Exceptions¶

The statement allows the programmer to force a specified
exception to occur. For example:

>>> raise NameError('HiThere')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: HiThere

The sole argument to indicates the exception to be raised.
This must be either an exception instance or an exception class (a class that
derives from ). If an exception class is passed, it will
be implicitly instantiated by calling its constructor with no arguments:

raise ValueError  # shorthand for 'raise ValueError()'

If you need to determine whether an exception was raised but don’t intend to
handle it, a simpler form of the statement allows you to
re-raise the exception:

Разбираемся с «with» в питоне (перевод)

18 февраля 2018 г.

Данная статья — перевод c моим небольшим дополнением, оригинал. 

Часто ключевое слово with не до конца понятно даже опытным разработчикам.

Как и многие другие вещи в Python, ключевое слово with на самом деле очень просто устроено, это станет очевидно, как только вы поймете какую проблему оно решает. Посмотрите на данный код:

1 set things up
2 try
3     do something
4 finally
5     tear things down

Здесь под «set things up» подразумевается открытие файла, подключение какого-то внешнего ресурса, а под «tear things down» — закрытие файла, отключение от внешнего ресурса. Конструкция try-finally гарантирует, что «tear things down» часть будет всегда исполнена, даже если код, делающий что-либо вызовет ошибку или не завершится.

Если это часто ипользуется, то было бы удобно вынести код  “set things up” и “tear things down” в библиотечную функцию, чтобы легко ее использовать. Конечно, вы можете сделать что-то вроде:

 1 def controlled_execution(callback):
 2     set things up
 3     try
 4         callback(thing)
 5     finally
 6         tear things down
 7 
 8 def my_function(thing):
 9     do something
10 
11 controlled_execution(my_function)

Но это немного многословно, особенно если вам нужно изменять локальные переменные. Другой подход заключается в использовании генератора, а затем нужно использовать for-in:

1 def controlled_execution():
2     set things up
3     try
4         yield thing
5     finally
6         tear things down
7 
8 for thing in controlled_execution():
9     do something with thing

Но yield нельзя было использовать внутри try-finally в 2.4 и раньше. И немного странно использовать loop для чего-то, что вы хотите выполнить один раз.

Поэтому, после рассмотрения нескольких вариантов, Гвидо Ван Россум и python-dev команда наконец решили использовать объект вместо генератора, чтобы контролировать поведение данного кода:

1 class controlled_execution
2     def __enter__(self):
3         set things up
4         return thing
5     def __exit__(self, type, value, traceback):
6         tear things down
7 
8 with controlled_execution() as thing
9     some code

Теперь, когда «with» выражение исполняется, Python исполняет выражение, вызывает метод __enter__ с полученным значением (которое называется «context guard»), затем присваивает переменной переданной словом as (в данном случае thing) то, что возвращает метод __enter__. Далее, Python исполняет тело (в данное случае some code), и в любом случае вызывает метод __exit__.

В добавок, __exit__ может подавить исключение, вернуть вместо него True. Например, этот __exit__ заменяет TypeError, но разрешает все другие исключения:

1 def __exit__(self, type, value, traceback):
2     return isinstance(value, TypeError)

Например:

 1 class controlled_execution
 2     def __enter__(self):
 3         print('in enter')
 4         print(self)
 5         return ('test')
 6 
 7     def __exit__(self, type, value, traceback):
 8         print('in exit')
 9 
10 
11 with controlled_execution() as thing
12     print('in here')
13     print(thing)
14     raise TypeError
alex@vostro:~/projects/blog_materials$ python test.py
in enter
<__main__.controlled_execution instance at 0x7f338bcb6a70>
in here
test
in exit
Traceback (most recent call last):
  File "test.py", line 14, in <module>
    raise TypeError
TypeError

Но:

 1 class controlled_execution
 2     def __enter__(self):
 3         print('in enter')
 4         print(self)
 5         return ('test')
 6 
 7     def __exit__(self, type, value, traceback):
 8         print('in exit')
 9         return isinstance(value, TypeError)
10 
11 
12 with controlled_execution() as thing
13     print('in here')
14     print(thing)
15     raise TypeError
alex@vostro:~/projects/blog_materials$ python test.py
in enter
<__main__.controlled_execution instance at 0x7ff3fac74a70>
in here
test
in exit

В Python 2.5 у объекта типа file появились методы __enter__ и __exit__, первый просто возвращает сам объект, а второй закрывает файл:

>>> f = open("x.txt")
>>> f
<open file 'x.txt', mode 'r' at 0x00AE82F0>
>>> f.__enter__()
<open file 'x.txt', mode 'r' at 0x00AE82F0>
>>> f.read(1)
'X'
>>> f.__exit__(None, None, None)
>>> f.read(1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: I/O operation on closed file

Поэтому, чтобы открыть файл, сделать что-то с содержимым и точно закрыть его, вы просто делаете так:

1 with open("x.txt") as f
2     data = f.read()
3     do something with data

Это не было очень сложно, правда?

Если вам понравился пост, можете поделиться им в соцсетях:

8.5. Exception Chaining¶

The statement allows an optional which enables
chaining exceptions. For example:

# exc must be exception instance or None.
raise RuntimeError from exc

This can be useful when you are transforming exceptions. For example:

>>> def func():
...     raise IOError
...
>>> try
...     func()
... except IOError as exc
...     raise RuntimeError('Failed to open database') from exc
...
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
  File "<stdin>", line 2, in func
OSError

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "<stdin>", line 4, in <module>
RuntimeError: Failed to open database

Exception chaining happens automatically when an exception is raised inside an
or section. Exception chaining can be
disabled by using idiom:

>>> try
...     open('database.sqlite')
... except OSError
...     raise RuntimeError from None
...
Traceback (most recent call last):
  File "<stdin>", line 4, in <module>
RuntimeError

Handling an exception

If you have some suspicious code that may raise an exception, you can defend your program by placing the suspicious code in a try: block. After the try: block, include an except: statement, followed by a block of code which handles the problem as elegantly as possible.

Syntax

Here is simple syntax of try….except…else blocks −

try:
   You do your operations here;
   ......................
except ExceptionI:
   If there is ExceptionI, then execute this block.
except ExceptionII:
   If there is ExceptionII, then execute this block.
   ......................
else:
   If there is no exception then execute this block. 

Here are few important points about the above-mentioned syntax −

  • A single try statement can have multiple except statements. This is useful when the try block contains statements that may throw different types of exceptions.

  • You can also provide a generic except clause, which handles any exception.

  • After the except clause(s), you can include an else-clause. The code in the else-block executes if the code in the try: block does not raise an exception.

  • The else-block is a good place for code that does not need the try: block’s protection.

Example

This example opens a file, writes content in the, file and comes out gracefully because there is no problem at all −

#!/usr/bin/python

try:
   fh = open("testfile", "w")
   fh.write("This is my test file for exception handling!!")
except IOError:
   print "Error: can\'t find file or read data"
else:
   print "Written content in the file successfully"
   fh.close()

This produces the following result −

Written content in the file successfully

Example

This example tries to open a file where you do not have write permission, so it raises an exception −

#!/usr/bin/python

try:
   fh = open("testfile", "r")
   fh.write("This is my test file for exception handling!!")
except IOError:
   print "Error: can\'t find file or read data"
else:
   print "Written content in the file successfully"

This produces the following result −

Error: can't find file or read data

Handling Multiple Exceptions with Except

We can define multiple exceptions with the same except clause. It means that if the Python interpreter finds a matching exception, then it’ll execute the code written under the except clause.

In short, when we define except clause in this way, we expect the same piece of code to throw different exceptions. Also, we want to take the same action in each case.

Please refer to the below example.

Example

try:
   You do your operations here;
   ......................
except(Exception1]]):
   If there is any exception from the given exception list,
   then execute this block.
   ......................
else:
   If there is no exception then execute this block

Raising an Exceptions

You can raise exceptions in several ways by using the raise statement. The general syntax for the raise statement is as follows.

Syntax

raise ]]

Here, Exception is the type of exception (for example, NameError) and argument is a value for the exception argument. The argument is optional; if not supplied, the exception argument is None.

The final argument, traceback, is also optional (and rarely used in practice), and if present, is the traceback object used for the exception.

Example

An exception can be a string, a class or an object. Most of the exceptions that the Python core raises are classes, with an argument that is an instance of the class. Defining new exceptions is quite easy and can be done as follows −

def functionName( level ):
   if level < 1:
      raise "Invalid level!", level
      # The code below to this would not be executed
      # if we raise the exception

Note: In order to catch an exception, an «except» clause must refer to the same exception thrown either class object or simple string. For example, to capture above exception, we must write the except clause as follows −

try:
   Business Logic here...
except "Invalid level!":
   Exception handling here...
else:
   Rest of the code here...

Extend except to Handle Exception Groups

We considered extending the semantics of except to handle
exception groups, instead of introducing except*. There were two
backwards compatibility concerns with this. The first is the type of the
caught exception. Consider this example:

try:
    . . .
except OSError as err:
    if err.errno != ENOENT:
        raise

If the value assigned to err is an exception group containing all of
the OSErrors that were raised, then the attribute access err.errno
no longer works. So we would need to execute the body of the except
clause multiple times, once for each exception in the group. However, this
too is a potentially breaking change because at the moment we write except
clauses with the knowledge that they are only executed once. If there is
a non-idempotent operation there, such as releasing a resource, the
repetition could be harmful.

Standard Exceptions

Here is a list of Standard Exceptions available in Python. −

Sr.No. Exception Name & Description
1

Exception

Base class for all exceptions

2

StopIteration

Raised when the next() method of an iterator does not point to any object.

3

SystemExit

Raised by the sys.exit() function.

4

StandardError

Base class for all built-in exceptions except StopIteration and SystemExit.

5

ArithmeticError

Base class for all errors that occur for numeric calculation.

6

OverflowError

Raised when a calculation exceeds maximum limit for a numeric type.

7

FloatingPointError

Raised when a floating point calculation fails.

8

ZeroDivisonError

Raised when division or modulo by zero takes place for all numeric types.

9

AssertionError

Raised in case of failure of the Assert statement.

10

AttributeError

Raised in case of failure of attribute reference or assignment.

11

EOFError

Raised when there is no input from either the raw_input() or input() function and the end of file is reached.

12

ImportError

Raised when an import statement fails.

13

KeyboardInterrupt

Raised when the user interrupts program execution, usually by pressing Ctrl&plus;c.

14

LookupError

Base class for all lookup errors.

15

IndexError

Raised when an index is not found in a sequence.

16

KeyError

Raised when the specified key is not found in the dictionary.

17

NameError

Raised when an identifier is not found in the local or global namespace.

18

UnboundLocalError

Raised when trying to access a local variable in a function or method but no value has been assigned to it.

19

EnvironmentError

Base class for all exceptions that occur outside the Python environment.

20

IOError

Raised when an input/ output operation fails, such as the print statement or the open() function when trying to open a file that does not exist.

21

OSError

Raised for operating system-related errors.

22

SyntaxError

Raised when there is an error in Python syntax.

23

IndentationError

Raised when indentation is not specified properly.

24

SystemError

Raised when the interpreter finds an internal problem, but when this error is encountered the Python interpreter does not exit.

25

SystemExit

Raised when Python interpreter is quit by using the sys.exit() function. If not handled in the code, causes the interpreter to exit.

26

TypeError

Raised when an operation or function is attempted that is invalid for the specified data type.

27

ValueError

Raised when the built-in function for a data type has the valid type of arguments, but the arguments have invalid values specified.

28

RuntimeError

Raised when a generated error does not fall into any category.

29

NotImplementedError

Raised when an abstract method that needs to be implemented in an inherited class is not actually implemented.

The try-finally Clause

You can use a finally: block along with a try: block. The finally: block is a place to put any code that must execute, whether the try-block raised an exception or not. The syntax of the try-finally statement is this −

try:
   You do your operations here;
   ......................
   Due to any exception, this may be skipped.
finally:
   This would always be executed.
   ......................

Note − You can provide except clause(s), or a finally clause, but not both. You cannot use else clause as well along with a finally clause.

Example

#!/usr/bin/python3

try:
   fh = open("testfile", "w")
   fh.write("This is my test file for exception handling!!")
finally:
   print ("Error: can\'t find file or read data")
   fh.close()

If you do not have permission to open the file in writing mode, then this will produce the following result −

Error: can't find file or read data

Same example can be written more cleanly as follows −

#!/usr/bin/python3

try:
   fh = open("testfile", "w")
   try:
      fh.write("This is my test file for exception handling!!")
   finally:
      print ("Going to close the file")
      fh.close()
except IOError:
   print ("Error: can\'t find file or read data")

This produces the following result −

Going to close the file

When an exception is thrown in the try block, the execution immediately passes to the finally block. After all the statements in the finally block are executed, the exception is raised again and is handled in the except statements if present in the next higher layer of the try-except statement.

Python Exception Обращаясь за лучшие практики

  • Всегда старайтесь обрабатывать исключение в коде, чтобы избежать ненормального завершения программы.
  • При создании таможенного класса исключения суффикс его название с «ошибкой».
  • Если кроме положения имеют тот же код, попробуйте поймать несколько исключений в одном кроме блока.
  • Используйте, наконец, блокировать, чтобы закрыть тяжелые ресурсы и удалить тяжелые объекты.
  • Используйте остальные блоки для журнала успешного выполнения кода, отправьте уведомления и т. Д.
  • Избегайте как можно большего размера, кроме как можно больше. Если вы не знаете об исключениях, то только используйте его.
  • Создание классов исключения для конкретных модулей для конкретных сценариев.
  • Вы можете ловить исключения в за исключением блоке, а затем поднять еще одно исключение, что является более значимым.
  • Всегда поднимайте исключения со значимыми сообщениями.
  • Избегайте вложенных блоков, кроме слоев, потому что это уменьшает читаемость кода.

Other Changes

Some changes to the language were made as part of the same project.

New Builtin Functions

Two new intrinsic functions for class testing were introduced
(since the functionality had to be implemented in the C API, there was
no reason not to make it accessible to Python programmers).

returns true iff class D is derived
from class C,
directly or indirectly. issubclass(C, C) always returns true. Both
arguments must be class objects.

returns true iff x is an
instance of C or of a
(direct or indirect) subclass of C. The first argument may hyave any
type; if x is not an instance of any class, isinstance(x, C) always
returns false. The second argument must be a class object.

Sequence Unpacking

Previous Python versions require an exact type match between the
left hand and right hand side of «unpacking» assignments, e.g.

As part of the same project, the right hand side of either statement can be
any sequence with exactly three items. This makes it possible to
extract e.g. the errno and strerror values from an IOError exception
in a backwards compatible way:

The same approach works for the SyntaxError exception, with the
proviso that the info part is not always present:

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

Adblock
detector