Errors & Exceptions
There are two major kinds of errors:
- Syntax Errors
- Exceptions
Syntax Errors
Syntax errors are parsing errors which occur when the code is not adhering to Python Syntax.
Code:
if True print("Hello")
Output
SyntaxError: invalid syntax
When there is a syntax error, the program will not execute even if that part of code is not used.
Code:
print("Hello")
def greet():
print("World"
Output
SyntaxError: unexpected EOF while parsing
Exceptions
Even when a statement or expression is syntactically correct, it may cause an error when an attempt is made to execute it.
Errors detected during execution are called exceptions.
Example Scenario
We wrote a program to download a Video over the Internet.
- Internet is disconnected during the download
- We do not have space left on the device to download the video
Example 1
Division Example
Input given by the user is not within expected values
Code
def divide(a, b):
return a / b
divide(5, 0)
Output
ZeroDivisionError: division by zero
Example 2
Input given by the user is not within expected values.
Code
def divide(a, b):
return a / b
divide("5", "10")
Output
TypeError: unsupported operand type(s) for /: ‘str’ and ‘str’
Example 3
Consider the following code, which is used to update the quantity of items in store.
Code
class Store:
def __init__(self):
self.items = {
"milk" : 20, "bread" : 30, }
def add_item(self, name, quantity):
self.items[name] += quantity
s = Store()
s.add_item('biscuits', 10)
Output
KeyError: ‘biscuits’
Working With Exceptions
What happens when your code runs into an exception during execution?
The application/program crashes.
End-User Applications
When you develop applications that are directly used by end-users, you need to handle different possible exceptions in your code so that the application will not crash.
Reusable Modules
When you develop modules that are used by other developers, you should raise exceptions for different scenarios so that other developers can handle them.
Raising Exceptions
When your code enters an unexpected state, raise an exception to communicate it.
Built-in Exceptions
Different exception classes which are raised in different scenarios.

You can use the built-in exception classes with raise keyword to raise an exception in the program.
Code
We can pass message as argument .
raise ValueError("Unexpected Value!!")
Output
ValueError:Unexpected Value!!
Handling Exceptions
Python provides a way to catch the exceptions that were raised so that they can be properly handled.
- Exceptions can be handled with try-except block.
- Whenever an exception occurs at some line in try block, the execution stops at that line and jumps to except block.
try:
# Write code that
# might cause exceptions.
except:
# The code to be run when
# there is an exception.
Example 1
Code
try:
a = int(input())
b = int(input())
c = a/b
print(c)
except ZeroDivisionError:
print("Denominator can't be 0")
except:
print("Unhandled Exception")
Input
5
0
Output
Denominator can’t be 0
Handling Multiple Exceptions
We can write multiple exception blocks to handle different types of exceptions differently.
Syntax
try:
# Write code that
# might cause exceptions.
except Exception1:
# The code to be run when
# there is an exception.
except Exception2:
# The code to be run when
# there is an exception.