Try/Except/Else/Finally Blocks

Errors

>>> print(I am super cool)
  File "<stdin>", line 1
    print(I am super cool)
             ^
SyntaxError: invalid syntax
Най-често срещаните съобщения, които виждаме, докато учим Python, са Error messages.

При изпълнението на кода, Python parser-ът е открил грешка. Съобщава ни за нея чрез името й(SyntaxError) и стрелка къде е възникнала.
>>> for i in range(3):
...     print(i)
...     print(2 * (2 / i))

Какво ще се изпълни?

>>> for i in range(3):
...     print(i)
...     print(2 * (2 / i))
... 
0
Traceback (most recent call last):
  File "<stdin>", line 3, in <module>
ZeroDivisionError: division by zero
Възникнала е грешка по време на изпълнение
Синтактично правилен код не ни гарантира, че програмата ни е валидна!
Errors(Грешки), хванати по време на изпълнение на кода, наричаме Exceptions(Изключения)!

Exceptions

>>> Roza + 'Roza'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'Roza' is not defined

>>> magic_number = 41 + '1'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'

>>> number = int("Some wild string")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'Some wild string'
  • Тип на грешката:
    Пример: TypeError, ValueError, ImportError, etc.

 

  • Описание на грешката:
    Пример: invalid literal for int() with base 10: 'Some wild string'

 

  • Къде е възникнала :
    Пример:  File "<stdin>", line 1, in <module>

Exception съобщението съдържа:

Как хващаме Exceptions?

Enter your age: 23
23
Enter your age: 44
44
Enter your age: ff
Traceback (most recent call last):
  File "handling_exceptions.py", line 7, in <module>
    age = int(input("Enter your age: "))
ValueError: invalid literal for int() with base 10: 'ff'
while True:
    age = int(input("Enter your age: "))
    print(age)

Как хващаме Exceptions?

Enter your age: 23
23
Enter your age: dd
Invalid number
Enter your age: 44
44
Enter your age: rozaaa
Invalid number
while True:
    try:
        age = int(input("Enter your age: "))
        print(age)
    except ValueError:
        print("Invalid number")

Как хващаме Exceptions?

Чрез Try/Except блок

try:
    pass # do something
except Exception:
    pass # catch one or more exceptions
else:
    pass # if try part is executed, execute and 'else' part of the block
finally:
    pass # part that executes after everything
try:
    f = open('text_file.txt')
except Exception as e:
    print('We hit an error: {}'.format(e))
else:
    print(f.read())
finally:
    if not f.closed:
        f.close()
В try клаузата се опитваме да отворим файл,

ако възникне каквато и да е грешка ще я хванем в except чрез класа Exception.

При успешно завършване на try, else частта ще бъде изпълнена. Finally се изпълнява винаги!

 

  • можем да хванем конкретна грешка

 

 

  • ако не знаем какви грешки могат да възникнат, съществува generic class Exception, който да извикаме

В except клаузата

try:
    f = open('some_file.txt')
except FileNotFoundError:
    print('''We hit an error! 
             This file does not exist!''')
try:
    file_name = input('Enter a file name: ')
    f = open(file_name)
    f.write(10 / 0)
except Exception as e:
    print('''Sorry, something went wrong! 
             You hit an error: {0}'''.format(e))
try:
    f = open('roza_custom_file')
    Roza = StrangeObject
except (FileNotFoundError, NameError) as e:
    print('Something went wrong')
try:
    file_name = input('Enter a file name: ')
    f = open(file_name)
    var = variable
except FileNotFoundError:
    print('We hit an error! This file does not exist!')
except NameError as e:
    print('You hit an error: {0}'.format(e))
Можем да хванем повече от една грешка
Ако искаме едно и също съобщение да се връща от няколко грешки, ги обединяваме!
>>> try:
...     n = (10/0)
... except:
...     raise RuntimeError("second message")

How to raise an exception

Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
ZeroDivisionError: division by zero

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 4, in <module>
RuntimeError: second message

Try/Except Blocks 2019

By Hack Bulgaria

Try/Except Blocks 2019

try/except blocks presentation on 6th of March 2019

  • 1,128