0% found this document useful (0 votes)
2 views

python43

The document discusses types of errors in Python, specifically syntax errors and exceptions, providing examples of each. It emphasizes the importance of handling exceptions in applications to prevent crashes and outlines how to raise and catch exceptions effectively. Additionally, it includes code snippets demonstrating proper exception handling techniques in various scenarios.

Uploaded by

Prachi More
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

python43

The document discusses types of errors in Python, specifically syntax errors and exceptions, providing examples of each. It emphasizes the importance of handling exceptions in applications to prevent crashes and outlines how to raise and catch exceptions effectively. Additionally, it includes code snippets demonstrating proper exception handling techniques in various scenarios.

Uploaded by

Prachi More
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

7/27/24, 9:54 PM Revolutionizing the Job Market | NxtWave

https://learning.ccbp.in/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=7f553143-459d-43df-a3fb-4749ed732353&s_id=d0867a5… 1/17
7/27/24, 9:54 PM Revolutionizing the Job Market | NxtWave

Errors & Exceptions

There are two major kinds of errors:

1. Syntax Errors
2. Exceptions

Syntax Errors

Syntax errors are parsing errors which occur when the code is not adhering
to Python Syntax.

Code
PYTHON

1 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
PYTHON

1 print("Hello")
2
3 def greet():
4 print("World"

https://learning.ccbp.in/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=7f553143-459d-43df-a3fb-4749ed732353&s_id=d0867a5… 2/17
7/27/24, 9:54 PM Revolutionizing the Job Market | NxtWave

Output

SyntaxError: unexpected EOF while parsing

Notice that in the above code, the syntax error is inside the

greet function, which is not used in rest of the code.

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

https://learning.ccbp.in/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=7f553143-459d-43df-a3fb-4749ed732353&s_id=d0867a5… 3/17
7/27/24, 9:54 PM Revolutionizing the Job Market | NxtWave

PYTHON

1 def divide(a, b):


2 return a / b
3
4 divide(5, 0)

Output

ZeroDivisionError: division by zero

Example 2

Input given by the user is not within expected values.

Code
PYTHON

1
2 def divide(a, b):
3 return a / b
4
5 divide("5", "10")

Output

TypeError: unsupported operand type(s) for /: 'str'

Example 3

Consider the following code, which is used to update the quantity of items
in store.

Code

PYTHON

https://learning.ccbp.in/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=7f553143-459d-43df-a3fb-4749ed732353&s_id=d0867a5… 4/17
7/27/24, 9:54 PM Revolutionizing the Job Market | NxtWave
1 class Store:
2 def __init__(self):
3 self.items = {
4 "milk" : 20, "bread" : 30, }
5
6 def add_item(self, name, quantity):
7 self.items[name] += quantity
8
9 s = Store()
10 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.

https://learning.ccbp.in/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=7f553143-459d-43df-a3fb-4749ed732353&s_id=d0867a5… 5/17
7/27/24, 9:54 PM Revolutionizing the Job Market | NxtWave

Money Transfer App Scenario

Let’s consider we are creating an app that allows users to transfer money
between them.

Bank Account Class

Example 1

Code

PYTHON
1 class BankAccount:
2 def __init__(self, account_number):
3 self.account_number = str(account_number)
4 self.balance = 0
5
6 def get_balance(self):
7 return self.balance
https://learning.ccbp.in/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=7f553143-459d-43df-a3fb-4749ed732353&s_id=d0867a5… 6/17
7/27/24, 9:54 PM Revolutionizing the Job Market | NxtWave

8
9 def withdraw(self, amount):
10 if self.balance >= amount:
11 self.balance -= amount

Expand

Output

User 1 Balance: 250/-


User 2 Balance: 100/-
Transferring 50/- from User 1 to User 2
User 1 Balance: 200/-
User 2 Balance: 150/-

Example 2

Code

PYTHON
1 class BankAccount:
2 def __init__(self, account_number):
3 self.account_number = str(account_number)
4 self.balance = 0
5
6 def get_balance(self):
7 return self.balance
8
9 def withdraw(self, amount):
10 if self.balance >= amount:
11 self balance -= amount
https://learning.ccbp.in/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=7f553143-459d-43df-a3fb-4749ed732353&s_id=d0867a5… 7/17
7/27/24, 9:54 PM Revolutionizing the Job Market | NxtWave
11 self.balance = amount

Expand

Output

User 1 Balance: 25/-


User 2 Balance: 100/-
Insufficient Funds
Transferring 50/- from User 1 to User 2
User 1 Balance: 25/-
User 2 Balance: 150/-

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.

https://learning.ccbp.in/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=7f553143-459d-43df-a3fb-4749ed732353&s_id=d0867a5… 8/17
7/27/24, 9:54 PM Revolutionizing the Job Market | NxtWave

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 .


PYTHON

1 raise ValueError("Unexpected Value!!")

Output

ValueError:Unexpected Value!!

Bank Account Class

Example 1

https://learning.ccbp.in/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=7f553143-459d-43df-a3fb-4749ed732353&s_id=d0867a5… 9/17
7/27/24, 9:54 PM Revolutionizing the Job Market | NxtWave

Code
PYTHON

1 class BankAccount:
2 def __init__(self, account_number):
3 self.account_number = str(account_number)
4 self.balance = 0
5
6 def get_balance(self):
7 return self.balance
8
9 def withdraw(self, amount):
10 if self.balance >= amount:
11 self.balance -= amount
Expand

Output

User 1 Balance: 25/-


User 2 Balance: 100/-

ValueError: Insufficient Funds

Handling Exceptions

https://learning.ccbp.in/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=7f553143-459d-43df-a3fb-4749ed732353&s_id=d0867a… 10/17
7/27/24, 9:54 PM Revolutionizing the Job Market | NxtWave

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.
PYTHON

1 try:
2 # Write code that
3 # might cause exceptions.
4 except:
5 # The code to be run when
6 # there is an exception.

Transfer Amount

Example 1

Code

PYTHON
1 class BankAccount:
2 def __init__(self, account_number):
3 self.account_number = str(account_number)
4 self.balance = 0
5
6 def get_balance(self):
7 return self.balance
8
https://learning.ccbp.in/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=7f553143-459d-43df-a3fb-4749ed732353&s_id=d0867a… 11/17
7/27/24, 9:54 PM Revolutionizing the Job Market | NxtWave
9 def withdraw(self, amount):
10 if self.balance >= amount:
11 self.balance -= amount

Expand

Output

User 1 Balance: 25/-


User 2 Balance: 100/-
False
Transferring 50/- from User 1 to User 2
User 1 Balance: 25/-
User 2 Balance: 100/-

Summary

Reusable Modules

While developing reusable modules, we need to raise Exceptions to


stop our code from being used in a bad way.

End-User Applications

While developing end-user applications, we need to handle Exceptions


so that application will not crash when used.

Handling Specific Exceptions

We can specifically mention the name of exception to catch all


exceptions of that specific type.

Syntax

https://learning.ccbp.in/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=7f553143-459d-43df-a3fb-4749ed732353&s_id=d0867a… 12/17
7/27/24, 9:54 PM Revolutionizing the Job Market | NxtWave

PYTHON

1 try:
2 # Write code that
3 # might cause exceptions.
4 except Exception:
5 # The code to be run when
6 # there is an exception.

Example 1

Code
PYTHON

1 try:
2 a = int(input())
3 b = int(input())
4 c = a/b
5 print(c)
6 except ZeroDivisionError:
7 print("Denominator can't be 0")
8 except:
9 print("Unhandled Exception")

Input

5
0

Output

Denominator can't be 0

Example 2

Code

https://learning.ccbp.in/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=7f553143-459d-43df-a3fb-4749ed732353&s_id=d0867a… 13/17
7/27/24, 9:54 PM Revolutionizing the Job Market | NxtWave

Input given by the user is not within expected values.


PYTHON

1 try:
2 a = int(input())
3 b = int(input())
4 c = a/b
5 print(c)
6 except ZeroDivisionError:
7 print("Denominator can't be 0")
8 except:
9 print("Unhandled Exception")

Input

12
a

Output

Unhandled Exception

We can also access the handled exception in an object.

Syntax
PYTHON

1 try:
2 # Write code that
3 # might cause exceptions.
4 except Exception as e:
5 # The code to be run when
6 # there is an exception.

Code

https://learning.ccbp.in/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=7f553143-459d-43df-a3fb-4749ed732353&s_id=d0867a… 14/17
7/27/24, 9:54 PM Revolutionizing the Job Market | NxtWave

PYTHON

1 class BankAccount:
2 def __init__(self, account_number):
3 self.account_number = str(account_number)
4 self.balance = 0
5
6 def get_balance(self):
7 return self.balance
8
9 def withdraw(self, amount):
10 if self.balance >= amount:
11 self.balance -= amount
Expand

Output

User 1 Balance: 25/-


User 2 Balance: 100/-
Insufficient Funds
<class 'ValueError'>
('Insufficient Funds',)
False
Transferring 50/- from User 1 to User 2
User 1 Balance: 25/-
User 2 Balance: 100/-

Handling Multiple Exceptions

We can write multiple exception blocks to handle different types of


exceptions differently.

Syntax

PYTHON
1 try:
2 # Write code that
3 # might cause exceptions.
4 except Exception1:
5 # The code to be run when
6 # there is an exception.
7 except Exception2:
8 # The code to be run when
9 # there is an exception
https://learning.ccbp.in/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=7f553143-459d-43df-a3fb-4749ed732353&s_id=d0867a… 15/17
7/27/24, 9:54 PM Revolutionizing the Job Market | NxtWave
9 # there is an exception.

Example 1

Code
PYTHON

1 try:
2 a = int(input())
3 b = int(input())
4 c = a/b
5 print(c)
6 except ZeroDivisionError:
7 print("Denominator can't be 0")
8 except ValueError:
9 print("Input should be an integer")
10 except:

Expand

Input

5
0

Output

Denominator can't be 0

Example 2

Code

PYTHON
1 try:
2 a = int(input())
3 b = int(input())
4 c = a/b
5 print(c)
6 except ZeroDivisionError:
7 print("Denominator can't be 0")
https://learning.ccbp.in/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=7f553143-459d-43df-a3fb-4749ed732353&s_id=d0867a… 16/17
7/27/24, 9:54 PM Revolutionizing the Job Market | NxtWave

8 except ValueError:
9 print("Input should be an integer")
10 except:

Expand

Input

12
a

Output

Input should be an integer

https://learning.ccbp.in/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=7f553143-459d-43df-a3fb-4749ed732353&s_id=d0867a… 17/17

You might also like