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

Exception_Handling - Jupyter Notebook

The document provides an overview of exception handling in Python, detailing the types of errors (syntax errors and exceptions) and common built-in exceptions such as SyntaxError, TypeError, and ZeroDivisionError. It explains the use of try and except statements for catching exceptions, along with the roles of else and finally blocks. Additionally, it discusses logical errors and how to raise exceptions using the raise keyword.

Uploaded by

subhampattnaik82
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Exception_Handling - Jupyter Notebook

The document provides an overview of exception handling in Python, detailing the types of errors (syntax errors and exceptions) and common built-in exceptions such as SyntaxError, TypeError, and ZeroDivisionError. It explains the use of try and except statements for catching exceptions, along with the roles of else and finally blocks. Additionally, it discusses logical errors and how to raise exceptions using the raise keyword.

Uploaded by

subhampattnaik82
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

4/1/24, 11:42 AM Exception - Jupyter Notebook

Exception Handling:

Error in Python can be of two types i.e. Syntax errors and Exceptio
ns. Errors are problems in a program due to which the program will
stop the execution. On the other hand, exceptions are raised when s
ome internal events occur which change the normal flow of the progr
am.

localhost:8888/notebooks/Desktop/PYTHON/16th Nov Python/Exception.ipynb 1/11


4/1/24, 11:42 AM Exception - Jupyter Notebook

Different types of exceptions in python: There are several built-in


exceptions that can be raised when an error occurs during the
execution of a program. Some of the most common types of
exceptions are :

SyntaxError: This exception is raised when the interpreter enco


unters a syntax error in the code, such as a misspelled keywor
d, a missing colon, or an unbalanced parenthesis.

TypeError: This exception is raised when an operation or functi


on is applied to an object of the wrong type, such as adding a
string to an integer.

NameError: This exception is raised when a variable or function


name is not found in the current scope.

IndexError: This exception is raised when an index is out of ra


nge for a list, tuple, or other sequence types.

KeyError: This exception is raised when a key is not found in a


dictionary
.
ValueError: This exception is raised when a function or method
is called with an invalid argument or input, such as trying to
convert a string to an integer when the string does not represe
nt a valid integer.

AttributeError: This exception is raised when an attribute or m


ethod is not found on an object, such as trying to access a non
-existent attribute of a class instance.

ZeroDivisionError: This exception is raised when an attempt is


made to divide a number by zero.

ImportError: This exception is raised when an import statement


fails to find or load a module.

In [1]: 1 # Syntax Error:


2 if 4%2:

Cell In[1], line 2


if 4%2:
^
SyntaxError: incomplete input

localhost:8888/notebooks/Desktop/PYTHON/16th Nov Python/Exception.ipynb 2/11


4/1/24, 11:42 AM Exception - Jupyter Notebook

In [2]: 1 # Type Error:


2 56+'cow'

--------------------------------------------------------------------------
-
TypeError Traceback (most recent call las
t)
Cell In[2], line 2
1 # Type Error:
----> 2 56+'cow'

TypeError: unsupported operand type(s) for +: 'int' and 'str'

In [3]: 1 # Indentation Error:


2 print('Hello')

Cell In[3], line 2


print('Hello')
^
IndentationError: unexpected indent

In [4]: 1 # Name Error:


2 a = 'kiwi'
3 print(var)

--------------------------------------------------------------------------
-
NameError Traceback (most recent call las
t)
Cell In[4], line 3
1 # Name Error:
2 a = 'kiwi'
----> 3 print(var)

NameError: name 'var' is not defined

In [5]: 1 # Index Error:


2 l = ['apple','mango','watermelon']
3 l[4]

--------------------------------------------------------------------------
-
IndexError Traceback (most recent call las
t)
Cell In[5], line 3
1 # Index Error:
2 l = ['apple','mango','watermelon']
----> 3 l[4]

IndexError: list index out of range

localhost:8888/notebooks/Desktop/PYTHON/16th Nov Python/Exception.ipynb 3/11


4/1/24, 11:42 AM Exception - Jupyter Notebook

In [6]: 1 # Attribute Error:


2 class One:
3 a = 12
4 b = 13
5
6 ob = One()
7 ob.c

--------------------------------------------------------------------------
-
AttributeError Traceback (most recent call las
t)
Cell In[6], line 7
4 b = 13
6 ob = One()
----> 7 ob.c

AttributeError: 'One' object has no attribute 'c'

In [7]: 1 # Zerodivision Error:


2 print(45/0)

--------------------------------------------------------------------------
-
ZeroDivisionError Traceback (most recent call las
t)
Cell In[7], line 2
1 # Zerodivision Error:
----> 2 print(45/0)

ZeroDivisionError: division by zero

In [8]: 1 # Import Error:


2 import mathematics

--------------------------------------------------------------------------
-
ModuleNotFoundError Traceback (most recent call las
t)
Cell In[8], line 2
1 # Import Error:
----> 2 import mathematics

ModuleNotFoundError: No module named 'mathematics'

localhost:8888/notebooks/Desktop/PYTHON/16th Nov Python/Exception.ipynb 4/11


4/1/24, 11:42 AM Exception - Jupyter Notebook

Syntax Error: As the name suggests this error is caused by the


wrong syntax in the code. It leads to the termination of the
program.

In [9]: 1 if 5>6

Cell In[9], line 1


if 5>6
^
SyntaxError: expected ':'

In [10]: 1 if 45%2!=0:
2 print 'Not divisible'

Cell In[10], line 2


print 'Not divisible'
^
SyntaxError: Missing parentheses in call to 'print'. Did you mean print
(...)?

Exceptions: Exceptions are raised when the program is


syntactically correct, but the code results in an error. This error
does not stop the execution of the program, however, it changes
the normal flow of the program.

In [11]: 1 num1 = int(input('Enter 1st number: '))


2 num2 = int(input('Enter 2nd number: '))
3 print(num1//num2)

Enter 1st number: 12


Enter 2nd number: 0

--------------------------------------------------------------------------
-
ZeroDivisionError Traceback (most recent call las
t)
Cell In[11], line 3
1 num1 = int(input('Enter 1st number: '))
2 num2 = int(input('Enter 2nd number: '))
----> 3 print(num1//num2)

ZeroDivisionError: integer division or modulo by zero

localhost:8888/notebooks/Desktop/PYTHON/16th Nov Python/Exception.ipynb 5/11


4/1/24, 11:42 AM Exception - Jupyter Notebook

Logical Error : Error related to logic, generates unexpected result.(


It cannot be handled with any error handling method )

In [12]: 1 a = 45
2 b = 30
3 if a<b:
4 print('a is greater')
5 else:
6 print('b is smaller')

b is smaller

Error handling is a process to capture any error and to


revoke(cancel) any unexpected termination.

Try and Except Statement – Catching Exceptions

Try and except statements are used to catch and handle exceptions i
n Python. Statements that can raise exceptions are kept inside the
try clause and the statements that handle the exception are written
inside except clause.
Syntax:
try:
# the statements that can generate error
except:
# statements that can be executed if any error is raised in
the try block.

The try block lets you test a block of code for errors.
The except block lets you handle the error.
The else block lets you execute code when there is no error.
The finally block lets you execute code, regardless of the resu
lt of the try- and except blocks.

In [13]: 1 # without try or except statement


2 var = 'aeroplane'
3 print(VAR)

--------------------------------------------------------------------------
-
NameError Traceback (most recent call las
t)
Cell In[13], line 3
1 # without try or except statement
2 var = 'aeroplane'
----> 3 print(VAR)

NameError: name 'VAR' is not defined

localhost:8888/notebooks/Desktop/PYTHON/16th Nov Python/Exception.ipynb 6/11


4/1/24, 11:42 AM Exception - Jupyter Notebook

In [14]: 1 # with try & except statement


2 try:
3 var = 'aeroplane'
4 print(VAR)
5
6 except:
7 print('''Error occured because of the variable name,check
8 the variable name once again''')

Error occured because of the variable name,check


the variable name once again

In [16]: 1 try:
2 var = 'aeroplane'
3 print(VAR)
4
5 except Exception as e:
6 print(e) # error message is shown
7 print('Type of Error:',type(e)) # type of the error is shown

name 'VAR' is not defined


Type of Error: <class 'NameError'>

In [17]: 1 """Except block is not executed if there is no error in the


2 program."""
3 try:
4 var = 'aeroplane'
5 print(var)
6
7 except Exception as e:
8 print(e) # error message is shown
9 print('Type of Error:',type(e)) # type of the error is shown

aeroplane

Else block:
Syntax:
try:
# Some Code....

except:
# optional block
# Handling of exception (if required)

else:
# execute if no exception

localhost:8888/notebooks/Desktop/PYTHON/16th Nov Python/Exception.ipynb 7/11


4/1/24, 11:42 AM Exception - Jupyter Notebook

In [19]: 1 try:
2 a = int(input('Enter 1st number: '))
3 b = int(input('Enter 2nd number: '))
4 c = a/b
5
6 except ZeroDivisionError:
7 print('Denominator cannot be 0.')
8 ​
9 except ValueError:
10 print('Give proper values for a & b.')
11
12 else:
13 print('The value of c:',c)

Enter 1st number: 45


Enter 2nd number: 0
Denominator cannot be 0.

In [20]: 1 try:
2 a = int(input('Enter 1st number: '))
3 b = int(input('Enter 2nd number: '))
4 c = a/b
5
6 except ZeroDivisionError:
7 print('Denominator cannot be 0.')
8 ​
9 except ValueError:
10 print('Give proper values for a & b.')
11
12 else:
13 print('The value of c:',c)

Enter 1st number: 45


Enter 2nd number: cat
Give proper values for a & b.

In [21]: 1 try:
2 a = int(input('Enter 1st number: '))
3 b = int(input('Enter 2nd number: '))
4 c = a/b
5
6 except ZeroDivisionError:
7 print('Denominator cannot be 0.')
8 ​
9 except ValueError:
10 print('Give proper values for a & b.')
11
12 else:
13 print('The value of c:',c)

Enter 1st number: 785


Enter 2nd number: 5
The value of c: 157.0

localhost:8888/notebooks/Desktop/PYTHON/16th Nov Python/Exception.ipynb 8/11


4/1/24, 11:42 AM Exception - Jupyter Notebook

Finally block :
Syntax:
try:
# Some Code....

except:
# optional block
# Handling of exception (if required)

else:
# execute if no exception

finally:
# Some code .....(always executed)

In [22]: 1 try:
2 a = int(input('Enter 1st number: '))
3 b = int(input('Enter 2nd number: '))
4 c = a/b
5
6 except ZeroDivisionError:
7 print('Denominator cannot be 0.')
8 ​
9 except ValueError:
10 print('Give proper values for a & b.')
11
12 else:
13 pass
14 ​
15 finally:
16 print('Value of c:',c)

Enter 1st number: 45


Enter 2nd number: 0
Denominator cannot be 0.
Value of c: 157.0

localhost:8888/notebooks/Desktop/PYTHON/16th Nov Python/Exception.ipynb 9/11


4/1/24, 11:42 AM Exception - Jupyter Notebook

In [23]: 1 try:
2 a = int(input('Enter 1st number: '))
3 b = int(input('Enter 2nd number: '))
4 c = a/b
5
6 except ZeroDivisionError:
7 print('Denominator cannot be 0.')
8 ​
9 except ValueError:
10 print('Give proper values for a & b.')
11
12 else:
13 pass
14 ​
15 finally:
16 print('Value of c:',c)

Enter 1st number: bat


Give proper values for a & b.
Value of c: 157.0

In [25]: 1 try:
2 a = int(input('Enter 1st number: '))
3 b = int(input('Enter 2nd number: '))
4 c = a/b
5
6 except ZeroDivisionError:
7 print('Denominator cannot be 0.')
8 ​
9 except ValueError:
10 print('Give proper values for a & b.')
11
12 else:
13 pass
14 ​
15 finally:
16 print('Value of c:',c) # optional block

Enter 1st number: 45


Enter 2nd number: bat
Give proper values for a & b.
Value of c: 157.0

Raise an exception : User can choose to throw an exception if a


condition occurs.
To throw (or raise) an exception, use the raise keyword.

In [26]: 1 num = int(input('Enter the number: '))


2 if num < 0:
3 raise Exception('Values cannot be in negative')

Enter the number: 156

localhost:8888/notebooks/Desktop/PYTHON/16th Nov Python/Exception.ipynb 10/11


4/1/24, 11:42 AM Exception - Jupyter Notebook

In [27]: 1 num = int(input('Enter the number: '))


2 if num < 0:
3 raise Exception('Values cannot be in negative')

Enter the number: -4521

--------------------------------------------------------------------------
-
Exception Traceback (most recent call las
t)
Cell In[27], line 3
1 num = int(input('Enter the number: '))
2 if num < 0:
----> 3 raise Exception('Values cannot be in negative')

Exception: Values cannot be in negative

localhost:8888/notebooks/Desktop/PYTHON/16th Nov Python/Exception.ipynb 11/11

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy