Hack Bulgaria
github.com/HackBulgaria
>>> print(This is a print message)
File "<stdin>", line 1
print(This is a print message)
^
SyntaxError: invalid syntax
Най-често срещаните съобщения, които виждаме, докато учим Python, са Error messages. При изпълнението на кода, Python parser-ът е открил грешка. Съобщава ни за нея чрез името й(SyntaxError) и стрелка къде е възникнала.
>>> for i in range(3):
... 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(Изключения)!
>>> 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>
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)
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")
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 се изпълнява винаги!
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))
Можем да хванем повече от една грешка
Ако искаме едно и също съобщение да се връща от няколко грешки, ги обединяваме!
By Hack Bulgaria