Hack Bulgaria
github.com/HackBulgaria
>>> print(invalid code)
File "<stdin>", line 1
print(invalid again)
^
SyntaxError: invalid syntax
>>> while True
File "<stdin>", line 1
while True
^
SyntaxError: invalid syntax
Syntax Errors occur during code parsing.
The parser show us where exactly the errors is (line X and ^ pointer)
>>> print(invalid)
>>> [x / x for x in range(10)]
>>> del 'I am a string!'[0]
>>> print(invalid)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'invalid' is not defined
>>> del 'I am a string'[0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object doesn't support item deletion
>>> [x/x for x in range(10)]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in <listcomp>
ZeroDivisionError: division by zero
while True:
try:
age = int(input('Enter your age: '))
print(age)
except ValueError:
print('Invalid input')
break
Enter your age: 10
10
Enter your age: 20
20
Enter your age: Marto
Invalid input
try:
pass # tries to execute the code here
except Exception:
pass # catches the exception from the try block
else:
pass # runs after ONLY IF try block succeeds
finally:
pass # executes after everything!
print('You have 10 inputs')
counter = 0
ages = []
while counter <= 10:
try:
age = int(input('Enter your age: '))
except ValueError:
print('Invalid input')
else:
ages.append(age)
finally:
counter += 1
person = {age: 23, name: 'Gosho'}
try:
job = person['job']
except KeyError:
print('''We found a person with no job.
Please, help him.''')
person = {age: 23, name: 'Gosho'}
try:
job = person['job']
new_age = person['age'] / 0
except Exception as e:
print('''Something went wrong.
The error was: {}'''.format(e))
using the base exception class
person = {age: 23, name: 'Gosho'}
try:
job = person['job']
new_age = person['age'] / 0
except KeyError:
print('There is no job.')
except ZeroDivisionError:
print('You cannot divide by 0')
using more than one exception class
person = {age: 23, name: 'Gosho'}
try:
job = person['job']
new_age = person['age'] / 0
except (KeyError, ZeroDivisionError) as err:
print(f'Something is wrong with the person: {err}')
try:
x = '10' / 0
except Exception:
raise TypeError('Marto is testing')
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
TypeError: unsupported operand type(s) for /: 'str' and 'int'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
TypeError: Marto is testing
By Hack Bulgaria