0% found this document useful (0 votes)
12 views10 pages

Ad - Python Ch-3 Notes

This document covers exception handling in Python, detailing types of errors such as syntax errors and logical errors, with examples for each. It explains how to use try-except blocks to handle exceptions, the raise keyword for raising exceptions, and the finally clause for cleanup actions. Additionally, it lists built-in exceptions and provides examples of handling specific and multiple exceptions.

Uploaded by

savaliyabhavy422
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)
12 views10 pages

Ad - Python Ch-3 Notes

This document covers exception handling in Python, detailing types of errors such as syntax errors and logical errors, with examples for each. It explains how to use try-except blocks to handle exceptions, the raise keyword for raising exceptions, and the finally clause for cleanup actions. Additionally, it lists built-in exceptions and provides examples of handling specific and multiple exceptions.

Uploaded by

savaliyabhavy422
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/ 10

Advanced Python Programming (UNIT-3) | 4321602

Unit-III: Exception Handling(Marks-14)


Explain Types of errors in python.-SUMMER-2023,WINTER-2022

What is Runtime error and Logical error. Explain with example. SUMMER-2022
Explain errors & exceptions
 Errors are problems that occur in the program due to an illegal operation performed by the user or by
the fault of a programmer, which halts the normal flow of the program. Errors are also termed bugs
or faults.
 There are mainly two types of errors in python programming.

Syntax errors
Logical Errors or Exceptions
 Whenever we do not write the proper syntax of the Python programming language (or any other
language) then the python interpreter throws an error known as a syntax error.
 On the other hand, Logical Errors are those errors that cannot be caught during compilation time.
 As we cannot check these errors during compile time, we name them Exceptions. Exceptions can
cause some serious issues so we should handle them effectively.

Note: Syntax errors can also be called Compile Time Error. Some of the most common compile-time
errors are syntax errors, library references, incorrect import of library functions and methods,
uneven bracket pair(s), etc.
Explain Syntax error and how do we identify it? Give an example.SUMMER-2022

Syntax Errors
 A syntax error is one of the most basic types of error in programming.
 Whenever we do not write the proper syntax of the python programming language (or any other
language) then the python interpreter or parser throws an error known as a syntax error.
 The syntax error simply means that the python parser is unable to understand a line of code.

Example:

number = 100

if number > 50
print("Number is greater than 50!")

O/P:
File "test.py", line 3
if number > 50
^
SyntaxError: invalid syntax

 As we can see in the example above, the python interpretation raised a syntax error saying invalid
syntax.
 We have missed the semicolon (:) after the if statement so that's why the python interpreter raised a
syntax error.

INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani , Mrs. Hina S. Jayani] 1


Advanced Python Programming (UNIT-3) | 4321602

 Some of the general syntax errors can be typing errors (errors), incorrect indentation, or incorrect
arguments.

Logical Errors
 Logical Errors are those errors that cannot be caught during compilation time.
 As we cannot check these errors during compile time, we name them Exceptions.
 Since we cannot check the logical errors during compilation time, it is difficult to find them.
 There is one more name of logical error. Run time errors are those errors that cannot be caught
during compilation time.
 So, run-time can cause some serious issues so we should handle them effectively.

Let us now talk about some of the most common logical types of errors in python programming.

ZeroDivisionError Exception
ZeroDivisionError is raised by the Python interpreter when we try to divide any number by zero. Let us take
an example to understand the ZeroDivisionError.

Example:
number = 100
divided_by_zero = number / 0

print(divided_by_zero)

O/P:
Traceback (most recent call last):
File "d:\test.py", line 2, in <module>
divided_by_zero = number / 0
ZeroDivisionError: division by zero

The Causes of exception mainly come from the environment where the code executes. For Example

 Reading a file that doesn’t exist


 Connecting to a remote server that is offline.
 Bad user inputs.
 Database doesn’t exists.

When an exception occurs, the programme doesn’t handle it automatically. This results in an error message.

Introduction to Exception
 An exception is an event, which occurs during the execution of a program that disrupts the normal
flow of the program's instructions.
 In general, when a Python script encounters a situation that it cannot cope with, it raises an
exception.
 An exception is a Python object that represents an error.

INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani , Mrs. Hina S. Jayani] 2


Advanced Python Programming (UNIT-3) | 4321602
 When a Python script raises an exception, it must either handle the exception immediately otherwise
it terminates and quits.

The Python interpreter shows a trackback that includes detailed information of the exception:
 The path to the source code file that caused the exception
 The exact line of code that caused the exception.
 The statement that caused the exception.
 The type of exception.
 The error message.

What are the built-in exceptions and gives its types.SUMMER 2022
List any Five built-in exceptions in python. SUMMER 2023,WINTER-2022

List types of Exception


Exception can be categorized in two types:
 Built-in Exceptions
 User defined Exception

Built-in Exceptions
 Python provides the number of built-in exception, but here we are describing the common standard
exceptions.
 A list of common exceptions that can be thrown from a standard Python program is given below.

Exception Description
ArithmeticError Raised when an error occurs in numeric calculations
Exception Base class for all exceptions
EOFError Raised when the input() method hits an "end of file" condition (EOF)
IndentationError Raised when indentation is not correct
MemoryError Raised when a program runs out of memory
NameError Raised when a variable does not exist
OSError Raised when a system related operation causes an error
SyntaxError Raised when a syntax error occurs
ValueError Raised when there is a wrong value in a specified data type
ZeroDivisionError Raised when the second operator in a division is zero

What is raise keyword? Explain with example WINTER-2022


Raising Exceptions
The raise statement in Python is used to raise an exception. Try-except blocks can be used to manage
exceptions, which are errors that happen while a programme is running. When an exception is triggered, the
programme goes to the closest exception handler, interrupting the regular flow of execution.

 The raise keyword is typically used inside a function or method, and is used to indicate an error
condition.

INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani , Mrs. Hina S. Jayani] 3


Advanced Python Programming (UNIT-3) | 4321602
 We can throw an exception and immediately halt the running of your programme by using the raise
keyword.
 Python looks for the closest exception handler, which is often defined using a try-except block, when
an exception is triggered.
 If an exception handler is discovered, its code is performed, and the try-except block's starting point
is reached again.
 If an exception handler cannot be located, the software crashes and an error message appears.

An illustration of how to raise an exception is provided below:

Example-1:
x = -1

if x < 0:
raise Exception("Sorry, no numbers below zero")
O/P:
Traceback (most recent call last):
File "demo_ref_keyword_raise.py", line 4, in <module>
raise Exception("Sorry, no numbers below zero")
Exception: Sorry, no numbers below zero

Assertion Error
 Assertion is a programming concept used while writing a code where the user declares a condition to
be true using assert statement prior to running the module.
 If the condition is True, the control simply moves to the next line of code. In case if it is False the
program stops running and returns AssertionError Exception.
 The function of assert statement is the same irrespective of the language in which it is implemented,
it is a language-independent concept, only the syntax varies with the programming language.

Syntax of assertion:
assert condition, error_message(optional)
Example : Assertion error with error_message.
# AssertionError with error_message.
x=1
y=0
assert y != 0, "Invalid Operation" # denominator can't be 0
print(x / y)
O/P:
Traceback (most recent call last):
File "/home/bafc2f900d9791144fbf59f477cd4059.py", line 4, in

INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani , Mrs. Hina S. Jayani] 4


Advanced Python Programming (UNIT-3) | 4321602
assert y!=0, "Invalid Operation" # denominator can't be 0
AssertionError: Invalid Operation
The default exception handler in python will print the error_message written by the programmer, or else will
just handle the error without any message.
Both of the ways are valid.
What is Exception handling in python? Explain with proper example.SUMMER-2022
Handling Exceptions
 While writing programs in python, there may be situations where the program enters into an
undesirable state called exceptions and exits the execution.
 This may cause loss of work done or may even cause memory leak.
 We will see how to handle those exceptions so that the program can continue executing in a normal
way using exception handling in python.
 We will also see what different ways to implement exception handling in python are.

Write points on Except and explaining it.SUMMER-2022


Explain the structure of try except. SUMMER-2023
Define following terms with syntax:1)Try 2) Except-WINTER-2022
Write a python program to demonstrate exception handling.-WINTER-2022
Implement Handling Exceptions
The following clauses are available in python to catch and handle exception
 Try clause
 Except clause
 Finally clause

The simplest way of handling exceptions in Python is by using the `try` and `except` block.
 Run the code under the `try` statement.
 When an exception is raised, execute the code under the `except` statement.

Instead of stopping at error or exception, our code will move on to alternative solutions.

INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani , Mrs. Hina S. Jayani] 5


Advanced Python Programming (UNIT-3) | 4321602
How try…except statements works?
First, the try clause is executed i.e. the code between try.
 If there is no exception, then only the try clause will run, except clause is finished.
 If any exception occurs, the try clause will be skipped and except clause will run.
 If any exception occurs, but the except clause within the code doesn’t handle it, it is passed on to the
outer try statements. If the exception is left unhandled, then the execution stops.
 A try statement can have more than one except clause

Example:
try:
print(x)
except:
print("An exception occurred")
O/P:
An exception occurred
Handle specific exception
 The try…exception statement allows you to handle a particular exception.
 To catch a selected exception, you place the type of exception after the except keyword

Example:
#The try block will generate a NameError, because x is not defined:

INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani , Mrs. Hina S. Jayani] 6


Advanced Python Programming (UNIT-3) | 4321602
try:
print(x)
except NameError:
print("Variable x is not defined")
except:
print("Something else went wrong")
O/P:
Variable x is not defined
Handle multiple exception
Suppose the code has a chance of raising multiple exceptions. The programmer needs to replace different
exceptions with different code, i.e., if they want to handle each exception differently, there is an option for
this too.
 One try statement can have multiple catch statements.
 We can catch a particular type of exception by mentioning the exception beside except in the except
block.

Syntax:
try:
# statements that might raise many exceptions
except One type of exception:
# code to replace
except another type of exception:
# code to replace
?
 If you want to have the same response to some type of exceptions, you can group them in one except
clause:

try:
# statements that might raise many exceptions
except (Exception1,Exception2):
# code to replace
Example:
try:
print(x/y)
except NameError:
print("Variable x is not defined")

INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani , Mrs. Hina S. Jayani] 7


Advanced Python Programming (UNIT-3) | 4321602
except ValueError:
print(“It’s not an Integer Vlaue")
except ZeroDivisionError:
print(“Division by Zero Error Occured")
O/P:
Variable x is not defined

Try with else block:

 We can use the try-except block along with an else block.


 According to the syntax, the else block must be placed after all the "except" blocks.
 If the code in the try block is successfully executed without raising any exceptions, else block will be
executed.

Example
num = int (input ("Enter the numerator: "))
den = int (input ("Enter the denominator: "))
try:
res = num/den
except ZeroDivisionError:
print ("The denominator cannot be zero")
else:
print ("The result of the division:", res)
O/P:
#Sample output-1-No exception rise
Enter the numerator: 3
Enter the denominator: 4
The result of the division: 0.75

#Sample output-2-Exception rise


Enter the numerator: 3
Enter the denominator: 0
The denominator cannot be zero
Write points on finally and explain with example.SUMMER-2023
Write a program to catch on Divide by Zero Exception with finally clause. SUMMER-2023
try…except…finally statement

INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani , Mrs. Hina S. Jayani] 8


Advanced Python Programming (UNIT-3) | 4321602
The try...except statement also has an optional clause called finally:
try:
# code that may cause exceptions
except:
# code that handle exceptions
finally:
# code that clean up
The finally clause always executes whether an exception occurs or not. And it executes after the try clause
and any except clause.
Example
a = 10
b=0
try:
c=a/b
print(c)
except ZeroDivisionError as error:
print(error)
finally:
print('Finishing up.')
O/P:
division by zero
Finishing up.
In this example, the try clause causes a ZeroDivisionError exception both except and finally clause executes.
The try clause in the following example doesn’t cause an error. Therefore, all statements in the try and
finally clauses execute:
Example
a = 10
b=2
try:
c=a/b
print(c)
except ZeroDivisionError as error:
print(error)

INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani , Mrs. Hina S. Jayani] 9


Advanced Python Programming (UNIT-3) | 4321602
finally:
print('Finishing up.')
Output:
5.0
Finishing up.

**********

“Do not give up, the beginning is always hardest!”

INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani , Mrs. Hina S. Jayani] 10

You might also like