07_Python_errors
07_Python_errors
>>> if x > 2
... print('x is greater than 2')
File "<ipython-input-73-00cd78beb41b>", line 1
if x > 2
^
SyntaxError: invalid syntax
Indentation error and missing parenthesis error
>>> if x > 2:
... print('x is greater than 2')
File "<ipython-input-74-544106e52c6f>", line 2
print('x is more than 2')
^
IndentationError: expected an indented block
>>> print'Hello'
File "<ipython-input-75-352cd0cc9337>", line 1
print 'Hello'
^
SyntaxError: Missing parentheses in call to 'print'
Exception
● Are syntactically correct
● List of built-in exceptions(Python 3.7)
>>> 3/0
Traceback (most recent call last):
try:
code block where exception can occur
except:
code block that will run if exception occurs
Catching exceptions
>>> try:
... print(3 + 3)
... print('x' + 3)
... print(2 + 2)
... except:
... print('Error occurred')
6
Error occurred
Raising Exception
● We can raise exception in our code using raise
>>> try:
... raise NameError
... except IOError:
... print('Input/Output error')
... except NameError:
... print('Object does not exist')
... except:
... print('Some unknown exception')
... else:
... print('Everything is OK!')
Exercise
● Ask user to type name
● Raise exception if name
○ Contains number
○ Has spaces
○ Does not start with uppercase letter
● If you code was working a minute ago, but now it doesn’t—what was the last thing you
changed?
● Reproduce problem
● Understand the error message. Do not be afraid of errors, they are here to help 🙂