Chapter 10 - Exception Handling in Python
- Authors
- Ms. Samavi Salman
- Dr. Rao Muhammad Adeel Nawab
- Supporting Material
Quick Recap
- Quick Recap – Best Coding Practices
In the previous Chapter, I presented the following main concepts:
- Coding Standards
- Coding Standards are collections of Coding rules, guidelines, and best practices
- Comment
- Comments are text notes added to a Program to provide explanatory information about the Source Code
- Types of Comments
- Single Line Comment
- Multi Line Comment
- Best Practices for Comments
- Some of the Best Practices in Commenting Code are as follows
- Comment your Code
- i.e., when writing your Code, also Comment your Code
- After completing the Coding (with proper Comments), again go through the entire Code (and Comments) and
- Check the quality of Comments
- Comments should be of high quality and self-explanatory
- i.e., anyone can understand your Code without taking any help from you
- Be consistent in the use of Commenting Style
- i.e., Use only one Commenting Style in all the Comments
- Before writing Comments of Code, your Comments should present the
- Copyright Information
- Authorship Information
- Main purpose of the Program
- Comments should be short, simple and easy to understand
- Comments should not mix up with the Code
- i.e., when writing your Code, also Comment your Code
- Comment your Code
- Some of the Best Practices in Commenting Code are as follows
- Software Documentation
- Any written text, illustrations or video that describes a Software to its Users is called Software Documentation (or Program Documentation)
- Guidelines for Creating High Quality Software Documentation
- To produce high quality Software Documentation some of the main guidelines are as follows
- Software Documentation should be
- complete and correct
- Software Documentation should be written from the
- point of view of the reader
- Software Documentation should follow the
- industry standards
- Consistency
- Consistency is defined as steadfast adherence to the same principles of Character over time
- PEP 8 – Official Coding Style Guide for Python
- PEP stands for Python Enhancement Proposal
- The PEP 8 is the Style Guide for Python Code and it mainly covers
- Formatting
- Comments
- Naming Conventions
- Indentation Style
- In Computer Programming, an Indentation Style is a convention governing the indentation of blocks of Code to convey Program Structure
- The PEP 8 is the Style Guide for Python Code and it mainly covers
- PEP stands for Python Enhancement Proposal
- Best Practices for Indentation
- In the Previous Slides, I identified 11 Best Practices for Indentation, which are as follows
- Best Practice 1
- Leave a Blank Line before Starting a Comment
- Best Practice 2
- There should be a Single Space on Left and Right Side of a Variable / Constant / Operator in a Python Statement
- Best Practice 3
- In an if Python Statement, Python Statement(s) after if Condition should be Indented with
- 4 Spaces
- In an if Python Statement, Python Statement(s) after if Condition should be Indented with
- Best Practice 4
- In an if-else Python Statement, Python Statement(s) after if Condition and else Python Statement should be Indented with
- 4 Spaces
- In an if-else Python Statement, Python Statement(s) after if Condition and else Python Statement should be Indented with
- Best Practice 5
- In a loop Python Statement, Python Statement(s) after loop Python Statement, should be Indented with
- 4 Spaces
- In a loop Python Statement, Python Statement(s) after loop Python Statement, should be Indented with
- Best Practice 6
- In a function Python Statement, Python Statement(s) after function Python Statement should be Indented with
- 4 Spaces
- In a function Python Statement, Python Statement(s) after function Python Statement should be Indented with
- Best Practice 7
- If a Python Statement is greater than 79 characters then
- Wrapping long lines inside parentheses, brackets and braces
- If a Python Statement is greater than 79 characters then
- Best Practice 8
- Usage of blank spaces
- After Class Definition use double blank spaces
- After Function / Method Definition use single blank space
- Best Practice 9
- In a Python Program, write one statement per line
- Best Practice 10
- In an import Python Statements, each import Python Statement should be on a separate line
- Best Practice 11
- In a Python Statement, use proper White Spaces in expressions and statements
- Consistency in Naming Scheme
- Set of rules for writing Identifiers and other entities in Source Code and Documentation of a Python Program is called Naming Scheme / Convention
- Consistency in Naming Scheme
- In a Python Statement, use proper White Spaces in expressions and statements
- Best Practice 1
- In the Previous Slides, I identified 11 Best Practices for Indentation, which are as follows
- Best Practices for Naming Convention
- In the Previous Slides, I identified 6 Best Practices for Naming Convention, which are as follows
- Best Practice 1
- Variable Name
- Variable Name should be in lower case
- Avoid using single character (x,y,z,l,i) variable name
- Use snake case for variable names
- User underscore to separate words in long variable names
- Use expressive variable names
- Avoid variable names that begin with a number
- Avoid using Special Characters (@,!,#,$) in variable names
- Best Practice 1
- Best Practice 2
- Constant Name
- Constants are usually declared and assigned values within a module
- The naming convention for constants is an aberration
- Constant names should be all CAPITAL letters
- Best Practice 3
- Function Argument
- If function argument name clashes with keyword use trailing underscore
- Use meaningful names
- The lowercase naming convention should be followed
- Function Argument
- Best Practice 4
- Module Name
- Prefer underscores for long module names
- Best Practice 5
- Package Name
- Avoid underscores for package names
- Best Practice 6
- Argument of Instance Method
- The first Argument of an Instance Method (the basic Class Method with no strings attached) should always be self
- This points to the Calling Object
- Best Practice 7
- Argument of Class Method
- The first argument of a class method should always be cls This points to the class, not the object instance
- Best Practice 8
- Follow CapWord (or camelCase) naming convention. Just start each word with a capital letter and do not include underscores between words
- PEP 8 suggests that you use CamelCase for class definitions
- If a class contains a subclass with the same attribute name, consider adding double underscores to the class attribute
- Best Practice 9
- Exception Classes
- Use the suffix Error for exception classes
- Best Practice 10
- Use of Underscore
- Single Leading Underscore _var
- Naming convention indicating name is meant for internal use. A hint for programmers and not enforced by programmers
- Double Leading and Trailing Underscore __var
- Triggers name mangling when used in class context. Enforced by the Python interpreter
- Underscore _
- Used as a name for temporary variables
- Single Leading Underscore _var
- Use of Underscore
- In the Previous Slides, I identified 6 Best Practices for Naming Convention, which are as follows
- Data and Code Organization
- File
- A File is the basic storage unit in a Computer
- Folder
- A Folder (a.k.a. Directory) holds one or more Files
- File
- Data and Code Organization
- Data and Code Organization refers to the systematic arrangement of Data and Code used in developing a Software
- Best Practices of Data and Code Organization
- In the Previous Slides, I identified 4 Best Practices for Data and Code Organization, which are as follows
- Best Practice 1
- Put One Project in One Directory / Folder
- Make separate Sub-directories / Sub-folders for
- Data
- Code
- Documentation
- In Data Sub-directory / Sub-folder
- Make Sub-sub-directories / Sub-sub-folders (If Needed)
- In Code Sub-directory / Sub-folder
- Make Sub-sub-directories / Sub-sub-folders (If Needed)
- In Documentation Sub-directory / Sub-folder
- Make Sub-sub-directories / Sub-sub-folders (If Needed)
- Best Practice 1
- Best Practice 2
- Use Relative Paths
- Best Practice 3
- Use Version Control System
- Best Practice 4
- Name of File / Folder should clearly reflect the content of the File / Folder
- File / Folder Naming Scheme / Conventions
- Use Consistent Computer Readable Naming Conventions
- Avoid spaces in file and dir names
- Use dashes-to-separate-words (slugs)
- Be Consistent When Naming Files – Use Lower Case/Upper Case
- Use Meaningful (Expressive) File and Directory Names
- Avoid special characters or spaces in a file name
- Avoid using final in file name
- Don’t Use Proprietary File Formats
- Proprietary formats are formats that require a specific tool (and a specific license often) to open. Examples include Excel (.xls) or Word (.doc)
- Write ReadMe files
- A README file contains information about other files in a directory or archive of computer software.
- A form of documentation, it is usually a simple plain text file called READ.ME , README
- In the Previous Slides, I identified 4 Best Practices for Data and Code Organization, which are as follows
- Code Grouping
- Code Grouping is defined as the process of grouping Code into blocks
- Best Practices for Code Grouping
- Below I present Best Practices for Code Grouping
- Best Practice 1
- Each blocks of code should be separated with some spaces between them
- Best Practice 1
- Below I present Best Practices for Code Grouping
- Exception
- An exception is an event, which occurs during the execution of a program that disrupts the normal flow of the program’s instructions
- Exception Handler
- An Exception Handler is a piece of Code that stipulates what a Program will do when an Exception occurs in a Program
- Exception Handling
- In Programming Languages, Exception Handling is defined as the mechanism of handling Exceptions (or Runtime Errors)
- Best Practices for Exception Handling
- Below I present Best Practices for Indentation
- Best Practice 1
- Use multiple except Statements when the try block contains Python Statements that may throw different types of Exceptions
- Best Practice 2
- Use a generic except clause, which handles any type of Exception
- i.e., except Exception:
- Use a generic except clause, which handles any type of Exception
- Note
- Exception can be used with alias name using
- as Keyword
- Exception can be used with alias name using
- Best Practice 3
- After except clause(s), you can include an else-Block
- Code in the else-Block executes if Code in the try Block does not raise an Exception
- The else-Block is a good place for Code that does not need the try Block’s protection
- Best Practice 1
- Best Practice 4
- Use finally Block for the piece of Code which should be executed in all situations
- Below I present Best Practices for Indentation
Basics of Exception Handling
- Exception vs Exception Handler
- Exception
- In a Programming Language, an Exception is defined as an unplanned event (or Runtime Error), which occurs during the execution of a Program and it disrupts the normal flow of the Program’s instructions
- What Happens When an Exception Occurs?
- When an Exception (unplanned event or error) occurs within a Function / Method, the Function / Method creates an object and hands it off to the Runtime System
- Exception Handler
- An Exception Handler is a piece of Code that stimulates what a Program will do when an Exception (Runtime Errors) occurs in a Program
- Exception Handling
- Definition
- In Programming Languages, Exception Handling is defined as the mechanism of handling Exception(s) (Runtime Errors) (or Runtime Error(s))
- Purpose
- Only Allah is Perfect 😊
- A Program made by Human cannot be Perfect and it will have
- Scope of Error
- The main purpose of Exception Handling is to
- Handle Runtime Error(s) which were not perceived by the Programmer(s) at the time of Program development
- Importance
- Exception Handling helps us to
- ensure that the flow of Program instructions does not break when an Exception(s) (Runtime Errors) occurs
- have meaningful Error Reporting
- Identify Error Types (for e.g., File Not Found, IO Exception etc.)
- Exception Handling helps us to
- Exception(s) and Python Programs
- In Python Programs, Exception(s) (Runtime Errors) are triggered in two main ways
- Automatically on Errors
- Intercepted by Code
- Exceptions and Python Cont…
- Question
- How to handle Exception(s) (Runtime Errors) in Python Programs?
- Answer
- There are many possible ways to Handle Exception(s) (Runtime Error(s)) in Python Program
- Insha Allah, I will discuss the following main Exception Handlers
- try / except
- Catch and recover from Exception(s) (Runtime Errors(s)) raised by a Python Program
- try / except / finally
- Catch and recover from Exception(s) (Runtime Error(s)) raised by a Python Program
- finally Block lets you execute Code, regardless of the result of the try and except Blocks
- try / except / else
- Catch and recover from Exception(s) raised by a Python Program
- else Block lets a Block of Code to be executed if no Error(s) were raised in try Block
- raise
- raise Statement allows you to Throw an Exception (Runtime Errors) in your Code and you can yourself define what kind of Error to raise
- try / except
Types of Exceptions in Python
- Types of Exceptions in Python
- Built in Exceptions
- User Defined Exceptions
- Built in Exceptions
- Definition
- A Built-in Exception is defined as an Exception which is generated either by an Interpreter or Built-in Function
- Built in Exceptions Cont….
- Question
- How to View Built-in Exceptions in Python?
- Answer
- Run the following Code
locals()['__builtins__']
- Built in Exceptions Cont….
- Some of the most common Built in Exceptions are as follows
- TypeError
- This Built in Exception is raised when we combine two different types
- ZeroDivisionError
- This Built in Exception is raised when we divide a number by ZERO
- SyntaxError
- This Built in Exception is raised when there is Syntax Error in the Code
- IndentationError
- This Built in Exception is raised when indentation is not properly (or incorrectly) used in the Code
- ValueError
- This Built in Exception is raised the value passed to an argument is improper
- RuntimeError
- This Built in Exception is generic and it is raised when the Runtime Error does not fall in any specific category of Exceptions
- NameError
- This Built in Exception is raised when a Variable is used that does not exist
- IndexError
- This Built in Exception is raised when an index of a List (or Sequence) is used that does not exist
- ArithmeticError
- This Built in Exception is raised when there is an Error in the numeric calculations
- TypeError
- User Defined Exception
- Definition
- A User Defined Exception is an Exception which is written by a Programmer
Exception Handling using try / except
- Variants of try / except Exception Handler in Python
- There are two main variants of try / except Exception Handler in Python
- Exception Handling using a Single except Statement
- Exception Handling using Multiple except Statements
- Insha Allah, in the next Slides I will discuss both of them in detail
Exception Handling using a Single except Statement
- Exception Handling using a Single except Statement
- Definition
- When we handle Exception(s) (Runtime Error(s)) using try / except
- try Block lets you Test a Block of Code for Exception(s) (or Runtime Error(s)) and
- except Block lets you handle the Exception (or Runtime Error) that was raised in the try Block
- Note
- In Exception Handling using a Single except Statement, you can have only
- one except Statement
- In Exception Handling using a Single except Statement, you can have only
- Purpose
- The main purpose of try / except is to handle Exception(s) (or Runtime Error(s)) in a Python Program
- Importance
- try / except helps you to handle Exception(s) (Runtime Error(s)) that were not perceived by a Programmer when he was writing the Code
- try / except is the most common and popular approach to handle Exception(s) (Runtime Error(s)) in Python Program
- Applications
- try / except helps a Programmer to enable flow control
- Suitable to Use
- A Programmer should use Exception Handlers in all Blocks of Codes
- Syntax - Exception Handling using a Single except Statement
try:
# Python Statements in try Block
except:
# Executed when Error occurs in Code inside try Block
- Example 1 – Exception Handling using a Single except Statement
- Given
- Write a Python Program which display the value of an Integer Variable on the Output Screen
- Task
- Your Code should have the ability to properly handle Exception(s) (Runtime Errors(s))
'''
__author__ = Ms. Samavi Salman
__copyright__= Copyright (C) 2020 Ms. Samavi Salman
__license__ = Public Domain
__version__ = 1.0
'''
'''
The main purpose of this Program is to print the value of an Integer Variable on Output Screen
'''
'''
In the following Code, Exception occurs because Variable 'number' is not defined
'''
try:
print(number)
except:
print("Error: Variable is not defined. Please declare the variable and then use it.")
Error: Variable is not defined. Please declare the variable and then use it.
- Remarks
- I used try / except for Exception Handling
- Will Program Generate Exception(s) (Runtime Error(s))?
- Yes
- Where was Exception(s) (Runtime Error(s)) Generated in the Python Program?
- In try Block of Code
- Where was Exception(s) (Runtime Error(s)) Handled in the Python Program?
- In except Block of Code
- Reason for Exception(s) (Runtime Error(s))
- The try block will generate an Exception (Runtime Error), because
- Variable (called number) is not defined in the Python Program
- The try block will generate an Exception (Runtime Error), because
- Conclusion
- Proper Exception Handling improves the overall quality of the Python Program
- Example 2 – Exception Handling using a Single except Statement
- Given
- Write a Python Program which display division of two Integer Variables on the Output Screen
- Task
- Your Code should have the ability to properly handle Exception(s) (Runtime Errors(s))
'''
__author__ = Ms. Samavi Salman
__copyright__= Copyright (C) 2020 Ms. Samavi Salman
__license__ = Public Domain
__version__ = 1.0
'''
'''
The main purpose of this program is to divide two Integer Variables and display the result on the Output Screen
'''
'''
In the following Program, Exception occurs because Variable ‘number1’ is divided Variable 'number2' i.e. Zero
'''
try:
number1 = 10
number2 = 0
result = number1 / number2
print(result)
except:
print("Error: Invalid Division. Number is divided by Zero ")
Error: Invalid Division. Number is divided by Zero
- Remarks
- I used try / except for Exception Handling
- Will Program Generate an Exception(s) (Runtime Error(s))?
- Yes
- Where was Exception(s) (Runtime Error(s)) Generated in the Python Program?
- In try Block of Code
- Where was Exception(s) (Runtime Error(s)) Handled in the Program?
- In except Block of Code
- Reason for Exception(s) (Runtime Error(s))
- The try block will generate an Exception (Runtime Error), because
- Variable (called number1) is divided by Zero which is Invalid
- Conclusion
- Proper Exception Handling improves the overall quality of the Python Program
- Example 3 – Exception Handling using a Single except Statement
- Given
- Write a Python Program which display the sum of two Integer Variables on the Output Screen
- Task
- Your Code should have the ability to properly handle Exception(s) (Runtime Error(s))
'''
__author__ = Ms. Samavi Salman
__copyright__= Copyright (C) 2020 Ms. Samavi Salman
__license__ = Public Domain
__version__ = 1.0
'''
'''
The main purpose of this Program is to display the sum of two Integer Variables on the Output Screen
'''
'''
In the following Program, Exception occurs because we are adding Integer (value of Variable 'number1') and String (value of Variable 'number2')
'''
try:
number1 = 8
number2 = '5'
sum = number1 + number2
print(sum)
except:
print("Error: Invalid Addition. Integer cannot be added with String")
Error: Invalid Addition. Integer cannot be added with String
- Remarks
- I used try / except for Exception Handling
- Will Program Generate an Exception(s) (Runtime Error(s))?
- Yes
- Where was Exception(s) (Runtime Error(s)) Generated in the Python Program?
- In try Block of Code
- Where was Exception(s) (Runtime Error(s)) Handled in the Python Program?
- In except Block of Code
- Reason for Exception(s) (Runtime Error(s))
- The try block will generate an Exception (Runtime Error), because
- Variable (called number1) is an Integer and Variable (called number2) is a String
- Integer and String cannot be added
- Conclusion
- Proper Exception Handling improves the overall quality of the Python Program
- Example 4 – Exception Handling using a Single except Statement
- Given
- Write a Python Program which display a List of Integers along with their indices on the Output Screen
- Task
- Your Code should have the ability to properly handle Exception(s) (Runtime Error(s)) Code
'''
__author__ = Ms. Samavi Salman
__copyright__= Copyright (C) 2020 Ms. Samavi Salman
__license__ = Public Domain
__version__ = 1.0
'''
'''
The main purpose of this Program is to display a List of Integers along with their indices on the Output Screen
'''
'''
In the following Program, Exception occurs because Variable (called 'numbers ') contains List of elements whose last element is at index 2
'''
try:
numbers = [1, 2, 3]
print("Second Element of List is: ", numbers[1])
print("Last Element of the List is: ", number[3])
except:
print("Error: Invalid Index Number. The last element of List is at index 2")
Second Element of List is: 2
Error: Invalid Index Number. The last element of List is at index 2
- Remarks
- I used try / except for Exception Handling
- Will Program Generate an Exception(s) (Runtime Error(s))?
- Yes
- Where was Exception(s) (Runtime Error(s)) Generated in the Python Program?
- In try Block of Code
- Where was Exception(s) (Runtime Error(s)) Handled in the Python Program?
- In except Block of Code
- Reason for Exception(s) (Runtime Error(s))
- The try block will generate an Exception (Runtime Error), because
- Variable (called number) contains List element with index number i.e., 2
- Conclusion
- Proper Exception Handling improves the overall quality of the Python Program
- Example 5 – Exception Handling using a Single except Statement
- Given
- Write a Python Program which divides 1 by each element of a List and display the results on the Output Screen
- Task
- Your Code should have the ability to properly handle Exception(s) (Runtime Error(s))
'''
__author__ = Ms. Samavi Salman
__copyright__= Copyright (C) 2020 Ms. Samavi Salman
__license__ = Public Domain
__version__ = 1.0
'''
'''
The main purpose of this Program is to divides 1 by the elements of a List and display the results on the Output Screen
'''
'''
In the following Program, Exception occurs because Variable (called 'numbers') contains List of elements whose last element is a String
'''
try:
numbers = [1, 2, 'a']
for number in numbers:
result = 1 / int(number)
print("1 /", number, "=", result)
except:
print("Error: Invalid Division. Integer Variable is divided by a String")
1 / 1 = 1.0
1 / 2 = 0.5
Error: Invalid Division. Integer Variable is divided by a String
- Remarks
- I used try / except for Exception Handling
- Will Program Generate an Exception(s) (Runtime Error(s))?
- Yes
- Where was Exception(s) (Runtime Error(s)) Generated in the Python Program?
- In try Block of Code
- Where was Exception(s) (Runtime Error(s)) Handled in the Python Program?
- In except Block of Code
- Reason for Exception(s) (Runtime Error(s))
- The try block will generate an Exception (Runtime Error), because
- Variable (called numbers) contains List whose last element is a String i.e., ’a’
- Conclusion
- Proper Exception Handling improves the overall quality of the Python Program
- Example 6 – Exception Handling using a Single except Statement
- Given
- Write a Python Program which display the division of two Integer Variables on the Output Screen
- Task
- Your Code should have the ability to properly handle Exception(s) (Runtime Errors(s))
'''
__author__ = Ms. Samavi Salman
__copyright__= Copyright (C) 2020 Ms. Samavi Salman
__license__ = Public Domain
__version__ = 1.0
'''
'''
The main purpose of this Program is to display the division of two Integer Variables on the Output Screen
'''
try:
number1 = 10
number2 = 2
result = int(number1 / number2)
print(result)
except ZeroDivisionError:
print("Error: Invalid Division. Number is divided by Zero")
5
- Remarks
- I used try / except for Exception Handling
- Will Program Generate an Exception(s) (Runtime Error(s))?
- No
- Where was Exception(s) (Runtime Error(s)) Generated in the Python Program?
- In try Block of Code
- Where was Exception(s) (Runtime Error(s)) Handled in the Program?
- In except Block of Code
- Reason for Exception(s) (Runtime Error(s))
- The try block will not generate any Exception (Runtime Error), because
- Variable (called number1) is divided by a Valid number
- Conclusion
- Proper Exception Handling improves the overall quality of the Python Program
TODO and Your Turn
TODO Task 1
- Task
- Consider the following four Python Programs and answer the following questions
Python Program 01 |
”’ __author__ = Ms. Samavi Salman __copyright__= Copyright (C) 2020 Ms. Samavi Salman __license__ = Public Domain __version__ = 1.0 ”’
”’ The main purpose of the Program is to take an Integer Variable as input from the User, add the number with ‘10’ and display the result on Output Screen ”’
try: number = input(“Enter an Integer number: “) sum = 10 + number print(sum) except: print(“Error: Invalid Input. String is not allowed. Please enter Integer”) |
Python Program 02 |
”’ __author__ = Ms. Samavi Salman __copyright__= Copyright (C) 2020 Ms. Samavi Salman __license__ = Public Domain __version__ = 1.0 ”’
”’ The main purpose of the Program is to take display a List of Integer elements at specific index on Output Screen ”’
try: number = 100 print(number[0]) except: print(“Error: Invalid number. Variable is an Integer. Not a List”) |
Python Program 03 |
”’ __author__ = Ms. Samavi Salman __copyright__= Copyright (C) 2020 Ms. Samavi Salman __license__ = Public Domain __version__ = 1.0 ”’
”’ The main purpose of the Program is to print a String on the Output Screen ”’
try: message = “ بےشک دلوں کا سکون اللہ کے ذکر میں ہے “ print(message) except SyntaxError: print(“Error: Invalid Syntax”) |
Python Program 04 |
”’ __author__ = Ms. Samavi Salman __copyright__= Copyright (C) 2020 Ms. Samavi Salman __license__ = Public Domain __version__ = 1.0 ”’
”’ The main purpose of the Program is to display subtraction of two Integer Variables on the Output Screen ”’
try: number1 = 500 number2 = 100 subtraction = number1 – number2 print(subtraction) except: print(“Error: Invalid Result. Number2 is greater than Number1”) |
- Note
- Your answer should be
- Well justified
- Your answer should be
- Questions
- Which Exception Handler is being used in the Python Programs to handle Exceptions?
- Which Python Programs generated Exception(s)?
- Where was Exception(s) (Runtime Error(s)) Generated in the Python Programs?
- Where was Exception(s) (Runtime Error(s)) Handled in the Python Program?
- What was the main reason for Exception(s) (Runtime Error(s))
- Write down your Findings / Conclusions after running the Python Programs?
Your Turn Task 1
- Task
- Write Five Python Programs using try /except Exception Handler and answer the questions given below
- Note
- Your answer should be
- Well justified
- Your answer should be
- Questions
- Which Exception Handler is being used in the Python Programs to handle Exceptions?
- Which Python Programs generated Exception(s)?
- Where was Exception(s) (Runtime Error(s)) Generated in the Python Programs?
- Where was Exception(s) (Runtime Error(s)) Handled in the Python Program?
- What was the main reason for Exception(s) (Runtime Error(s))
- Write down your Findings / Conclusions after running the Python Programs?
Exception Handling using Multiple except Statements
- Exception Handling using Multiple except Statements
- Definition
- When we handle Exception(s) (Runtime Error(s)) using try / except
- try Block lets you Test a Block of Code for Exception(s) (or Runtime Error(s)) and
- except Block lets you handle the Exception(s) (or Runtime Error(s)) that was raised in the try Block
- Note
- In Exception Handling using Multiple except Statements, you can have
- Multiple (more than one) except Statements
- Purpose
- The main purpose of try / except is to handle Exception(s) (or Runtime Error(s)) in a Python Program
- Importance
- try / except helps you to handle Exception(s) (Runtime Error(s)) that were not perceived by a Programmer when he was writing the Code
- try / except is the most common and popular approach to handle Exception(s) (Runtime Error(s)) in Python Program
- Applications
- try / except helps a Programmer to enable flow control
- Suitable to Use
- A Programmer should use Exception Handlers in all Blocks of Codes
- Syntax - Exception Handling using Multiple except Statements
- The Table below shows Syntax of
- Exception Handling using Multiple except Statements
- Importance Note
- Once an except is executed
- all the excepts following it will be ignored
try:
# Python Statements in try Block
except:
# Executed when Error occurs in Code inside try Block
except:
# Executed when Error occurs in Code inside try Block
except:
# Executed when Error occurs in Code inside try Block
- Example 1 – Exception Handling using Multiple except Statements
- Given
- Write a Python Program which display the value of an Integer Variable on the Output Screen
- Task
- Your Code should have the ability to properly handle Exception(s) (Runtime Errors(s))
'''
__author__ = Ms. Samavi Salman
__copyright__= Copyright (C) 2020 Ms. Samavi Salman
__license__ = Public Domain
__version__ = 1.0
'''
'''
The main purpose of this Program is to print the value of an Integer Variable on Output Screen
'''
'''
In the following Code, Exception occurs because Variable 'number' is not defined
'''
try:
print(number3)
except ValueError:
print("Sorry! Some other error occurred ")
except NameError:
print("Error: Variable is not defined. Please declare the variable and then use it. ")
Error: Variable is not defined. Please declare the variable and then use it.
- Remarks
- I used try / except for Exception Handling
- Will Program Generate Exception(s) (Runtime Error(s))?
- Yes
- Where was Exception(s) (Runtime Error(s)) Generated in the Python Program?
- In try Block of Code
- Where was Exception(s) (Runtime Error(s)) Handled in the Python Program?
- In except Block of Code
- Reason for Exception(s) (Runtime Error(s))
- The try block will generate an Exception (Runtime Error), because
- Variable (called number) is not defined in the Python Program
- Conclusion
- Proper Exception Handling improves the overall quality of the Python Program
- Example 2 – Exception Handling using Multiple except Statements
- Given
- Write a Python Program which display the value of an Integer Variable on the Output Screen
- Task
- Your Code should have the ability to properly handle Exception(s) (Runtime Errors(s))
'''
__author__ = Ms. Samavi Salman
__copyright__= Copyright (C) 2020 Ms. Samavi Salman
__license__ = Public Domain
__version__ = 1.0
'''
'''
The main purpose of this Program is to print the value of an Integer Variable on Output Screen
'''
'''
In the following Code, Exception occurs because Variable 'number' is a String not an Integer
'''
try:
number4 = int(input("Enter an Integer Number:" ))
print(number4)
except NameError:
print("Error: Variable is not defined. Please declare the variable and then use it. ")
except ValueError:
print("Error: Only Integers are allowed as Input")
Enter an Integer Number:s
Error: Only Integers are allowed as Input
- Remarks
- I used try / except for Exception Handling
- Will Program Generate Exception(s) (Runtime Error(s))?
- Yes
- Where was Exception(s) (Runtime Error(s)) Generated in the Python Program?
- In try Block of Code
- Where was Exception(s) (Runtime Error(s)) Handled in the Python Program?
- In except Block of Code
- Reason for Exception(s) (Runtime Error(s))
- The try block will generate an Exception (Runtime Error), because
- Variable (called number) is initialized with String not Integer
- Conclusion
- Proper Exception Handling improves the overall quality of the Python Program
- Example 3 – Exception Handling using Multiple except Statements
- Given
- Write a Python Program which display division of two Positive Integer Variables on the Output Screen
- Task
- Your Code should have the ability to properly handle Exception(s) (Runtime Errors(s))
'''
__author__ = Ms. Samavi Salman
__copyright__= Copyright (C) 2020 Ms. Samavi Salman
__license__ = Public Domain
__version__ = 1.0
'''
'''
The main purpose of this Program is to display division of two Positive Integer Variables on the Output Screen
'''
'''
In the following Program, Exception occurs because Variable ‘number1’ is divided by Variable 'number2' i.e. Zero
'''
try:
number1 = 10
number2 = 0
result = int(number1 / number2)
print(result)
except ZeroDivisionError:
print("Error: Invalid Division. Number is divided by Zero")
except ValueError:
print("Error: Invalid Division. Dividend is a Negative Integer")
Error: Invalid Division. Number is divided by Zero
- Remarks
- I used try / except for Exception Handling
- Will Program Generate an Exception(s) (Runtime Error(s))?
- Yes
- Where was Exception(s) (Runtime Error(s)) Generated in the Python Program?
- In try Block of Code
- Where was Exception(s) (Runtime Error(s)) Handled in the Program?
- In except Block of Code
- Reason for Exception(s) (Runtime Error(s))
- The try block will generate an Exception (Runtime Error), because
- Variable (called number1) is divided by Zero which is Invalid
- Conclusion
- Proper Exception Handling improves the overall quality of the Python Program
TODO and Your Turn
TODO Task 1
- Task
- Consider the following five Python Programs and answer the following questions
Python Program 01 |
”’ __author__ = Ms. Samavi Salman __copyright__= Copyright (C) 2020 Ms. Samavi Salman __license__ = Public Domain __version__ = 1.0 ”’ ”’ The main purpose of the Program is to take a number as input from User, add the number with ‘10’ and display the result on Output Screen ”’ try: number = input(“Enter an Integer number: “) number = 10 + number print(number) except: print(“Error: Invalid Input. String is not allowed. Please enter Integer”) except: print(“Error: Invalid Input. Floating number is not allowed. Please enter an Integer number.”) |
Python Program 02 |
”’ __author__ = Ms. Samavi Salman __copyright__= Copyright (C) 2020 Ms. Samavi Salman __license__ = Public Domain __version__ = 1.0 ”’ ”’ The main purpose of the Program is to take display a List of Integer elements at specific index on the Output Screen ”’ try: number = 100 print(number[0]) except: print(“Error: Invalid number. Variable is an Integer not a List”) except: print(“Error: Invalid number. Variable is a float not a List”) |
Python Program 03 |
”’ __author__ = Ms. Samavi Salman __copyright__= Copyright (C) 2020 Ms. Samavi Salman __license__ = Public Domain __version__ = 1.0 ”’ ”’ The main purpose of the Program is to print a String and display it on Output Screen ”’ try: message = “ بےشک دلوں کا سکون اللہ کے ذکر میں ہے “ print(message) except SyntaxError: print(“Error: Invalid Syntax”) except NameError: print(“Error: Invalid Input. Variable is not defined”) |
Python Program 04 |
”’ __author__ = Ms. Samavi Salman __copyright__= Copyright (C) 2020 Ms. Samavi Salman __license__ = Public Domain __version__ = 1.0 ”’ ”’ The main purpose of the Program is to display subtraction of two Integer Variables on the Output Screen ”’ try: number1 = 500 number2 = ‘100’ subtraction = number1 – number2 print(subtraction) except: print(“Error: Invalid number. Number2 is greater than number1”) except: print(“Error: Invalid number. Number2 is a String”) |
Python Program 05 |
”’ __author__ = Ms. Samavi Salman __copyright__= Copyright (C) 2020 Ms. Samavi Salman __license__ = Public Domain __version__ = 1.0 ”’ ”’ The main purpose of the Program is to display subtraction of two Integer Variables on the Output Screen ”’ try: number1 = 500 number2 = 100 result = number1 – number2 print(result) except: print(“Error: Invalid Result. Number2 is a String”) except: print(“Error: Invalid Result. Number1 is a String”) |
- Note
- Your answer should be
- Well justified
- Your answer should be
- Questions
- Which Exception Handler is being used in the Python Programs to handle Exceptions?
- Which Python Programs generated Exception(s)?
- Where was Exception(s) (Runtime Error(s)) Generated in the Python Programs?
- Where was Exception(s) (Runtime Error(s)) Handled in the Python Program?
- What was the main reason for Exception(s) (Runtime Error(s))
- Write down your Findings / Conclusions after running the Python Programs?
Your Turn Task 1
- Task
- Write Five Python Programs using try with multiple except Exception Handler and answer the questions given below
- Note
- Your answer should be
- Well justified
- Your answer should be
- Questions
- Which Exception Handler is being used in the Python Programs to handle Exceptions?
- Which Python Programs generated Exception(s)?
- Where was Exception(s) (Runtime Error(s)) Generated in the Python Programs?
- Where was Exception(s) (Runtime Error(s)) Handled in the Python Program?
- What was the main reason for Exception(s) (Runtime Error(s))
- Write down your Findings / Conclusions after running the Python Programs?
Exception Handling using try / except / else
- Exception Handling using try / except / else
- Definition
- When we handle Exception(s) (Runtime Error(s)) using try / except / else
- try Block lets you Test a Block of Code for Exception(s) (or Runtime Error(s)) and
- except Block lets you handle the Exception (or Runtime Error) that was raised in the try Block
- else Block of Code will be executed only if no Exception(s) is generated in try Block of Code
- Note
- In Exception Handling using try / except / else, you can have
- only one except Statements
- Exception(s) in the else clause are not handled by the preceding except clauses
- In Exception Handling using try / except / else, you can have
- Purpose
- The main purpose of try / except / else Exception Handler is to
- add more flexibility to the try / except Exception Handler by allowing you to execute Code when no Exception is generated in try Blocks of Code
- The main purpose of try / except / else Exception Handler is to
- Importance
- try / except / else helps you to handle Exception(s) (Runtime Error(s)) that were not perceived by a Programmer when he was writing the Code
- try / except / else provides you more flexibility by allowing you to execute Block of Code when no Exception is generated in try Blocks of Code
- try / except / finally is one of the common and popular approach to handle Exception(s) (Runtime Error(s)) in Python Program
- Applications
- try / except / else helps a Programmer to enable flow control
- Suitable to Use
- try / except / finally is more suitable to use when we want to execute a Block of Code, when no Exception is generated in try Block of Code
- A Programmer should use Exception Handlers in all Blocks of Codes
- Syntax - Exception Handling using try / except / else
try:
# Python Statements in try Block
except:
# Executed when Exception is generated inside try Block
else:
# Executed when Exception is not generated inside try Block
- Example 1 – Exception Handling using try / except / else
- Given
- Write a Python Program which display the value of an Integer Variable on the Output Screen
- Task
- Your Code should have the ability to properly handle Exception(s) (Runtime Errors(s))
'''
__author__ = Ms. Samavi Salman
__copyright__= Copyright (C) 2020 Ms. Samavi Salman
__license__ = Public Domain
__version__ = 1.0
'''
'''
The main purpose of this Program is to print the value of an Integer Variable on Output Screen
'''
'''
In the following Code, else Block is executed because Variable 'number' is defined
'''
try:
number = 10
print(number)
except:
print("Error: Variable is not defined. Please declare the variable and then use it. ")
else:
print("Value of variable is: ", number)
10
Value of variable is: 10
- Remarks
- I used try / except for Exception Handling
- Will Program Generate Exception(s) (Runtime Error(s))?
- No
- Reason for Executing else block
- The else block will be executed because
- Variable (called number) is defined in the Python Program
- The else block will be executed because
- Conclusion
- Proper Exception Handling improves the overall quality of the Python Program
- Example 2 – Exception Handling using try / except / else
- Given
- Write a Python Program which display the value of an Integer Variable on the Output Screen
- Task
- Your Code should have the ability to properly handle Exception(s) (Runtime Errors(s))
'''
__author__ = Ms. Samavi Salman
__copyright__= Copyright (C) 2020 Ms. Samavi Salman
__license__ = Public Domain
__version__ = 1.0
'''
'''
The main purpose of this Program is to print the value of an Integer Variable on Output Screen
'''
'''
In the following Code, except Block is executed because Variable 'number' is defined
'''
try:
print(number5)
except:
print("Error: Variable is not defined. Please declare the variable and then use it.")
Error: Variable is not defined. Please declare the variable and then use it.
- Remarks
- I used try / except for Exception Handling
- Will Program Generate Exception(s) (Runtime Error(s))?
- No
- Reason for Executing else block
- The except block will be executed because
- Variable (called number) is not defined in the Python Program
- The except block will be executed because
- Conclusion
- Proper Exception Handling improves the overall quality of the Python Program
- Example 3 – Exception Handling using try / except / else
- Given
- Write a Python Program which display division two Integer Variables on the Output Screen
- Task
- Your Code should have the ability to properly handle Exception(s) (Runtime Errors(s))
'''
__author__ = Ms. Samavi Salman
__copyright__= Copyright (C) 2020 Ms. Samavi Salman
__license__ = Public Domain
__version__ = 1.0
'''
'''
The main purpose of this Program is to display division two Integer Variables on the Output Screen
'''
'''
In the following Program, else Block is executed because Variable ‘number1’ is divided by Variable "number2" i.e. not Zero
'''
try:
number1 = 10
number2 = 6
result = number1 / number2
print(result)
except:
print("Error: Invalid Division. Number is divided by Zero")
else:
print("The result is: ", result)
1.6666666666666667
The result is: 1.6666666666666667
- Remarks
- I used try / except for Exception Handling
- Will Program Generate an Exception(s) (Runtime Error(s))?
- No
- Reason for Executing else block
- The else block will be executed because
- Variable (called number1) is divided with Variable (called number2) i.e. Valid Integers
- The else block will be executed because
- Conclusion
- Proper Exception Handling improves the overall quality of the Python Program
- Example 4 – Exception Handling using try / except / else
- Given
- Write a Python Program which display division two Integer Variables on the Output Screen
- Task
- Your Code should have the ability to properly handle Exception(s) (Runtime Errors(s))
'''
__author__ = Ms. Samavi Salman
__copyright__= Copyright (C) 2020 Ms. Samavi Salman
__license__ = Public Domain
__version__ = 1.0
'''
'''
The main purpose of this Program is to display division two Integer Variables on the Output Screen
'''
'''
In the following Program, except Block is executed because Variable ‘number1’ is divided by Variable ‘number2’ i.e. Zero
'''
try:
number1 = 10
number2 = 0
result = number1 / number2
print(result)
except:
print("Error: Invalid Division. Number is divided by Zero")
else:
print("The result is: ", result)
Error: Invalid Division. Number is divided by Zero
- Remarks
- I used try / except for Exception Handling
- Will Program Generate an Exception(s) (Runtime Error(s))?
- No
- Reason for Executing else block
- The exception block will be executed because
- Variable (called number1) is divided with Zero which is Invalid
- The exception block will be executed because
- Conclusion
- Proper Exception Handling improves the overall quality of the Python Program
- Example 5 – Exception Handling using try / except / else
- Given
- Write a Python Program which divides 1 by the elements of a List and display the results on the Output Screen
- Task
- Your Code should have the ability to properly handle Exception(s) (Runtime Error(s))
'''
__author__ = Ms. Samavi Salman
__copyright__= Copyright (C) 2020 Ms. Samavi Salman
__license__ = Public Domain
__version__ = 1.0
'''
'''
The main purpose of this Program is to divides 1 by each element of List and display the results on the Output Screen
'''
'''
In the following Program, else Block is executed because Variable (called numbers) contains List of Integers
'''
try:
numbers = [1, 2, 3]
for number in numbers:
print("1 /", number, "=", number, "The number is: ", number)
divide = 1 / int(number)
except:
print("Error: Invalid Division. Integer Variable is divided by a String")
else:
print("The result is: " , divide)
1 / 1 = 1 The number is: 1
1 / 2 = 2 The number is: 2
1 / 3 = 3 The number is: 3
The result is: 0.3333333333333333
- Remarks
- I used try / except for Exception Handling
- Will Program Generate an Exception(s) (Runtime Error(s))?
- No
- Reason for Executing else block
- The else block will be executed because
- Variable (called numbers) contains List of Integers
- The else block will be executed because
- Conclusion
- Proper Exception Handling improves the overall quality of the Python Program
- Example 6 – Exception Handling using try / except / else
- Given
- Write a Python Program which divides 1 by the elements of a List and display the results on the Output Screen
- Task
- Your Code should have the ability to properly handle Exception(s) (Runtime Error(s))
'''
__author__ = Ms. Samavi Salman
__copyright__= Copyright (C) 2020 Ms. Samavi Salman
__license__ = Public Domain
__version__ = 1.0
'''
'''
The main purpose of this Program is to divides 1 by the elements of a List and display the results on the Output Screen
'''
'''
In the following Program, except Block is executed because Variable (called numbers) contains List of Integers
'''
try:
numbers = [1, 2, 'a']
for number in numbers:
divide = 1 / int(number)
print("1 /", number, "=", divide)
except:
print("Error: Invalid Division. Integer Variable is divided by a String")
else:
print("The result is: " , divide)
1 / 1 = 1.0
1 / 2 = 0.5
Error: Invalid Division. Integer Variable is divided by a String
- Remarks
- I used try / except for Exception Handling
- Will Program Generate an Exception(s) (Runtime Error(s))?
- No
- Reason for Executing else block
- The exception block will be executed because
- Variable (called numbers) contains String element in a List
- The exception block will be executed because
- Conclusion
- Proper Exception Handling improves the overall quality of the Python Program
TODO and Your Turn
TODO Task 1
- Task
- Consider the following three Python Programs and answer the following questions
Python Program 01 |
”’ __author__ = Ms. Samavi Salman __copyright__= Copyright (C) 2020 Ms. Samavi Salman __license__ = Public Domain __version__ = 1.0 ”’
”’ The main purpose of this Program is to take a List of Integers and display the value at specific index on the Output Screen ”’
try: number = [10,20,30,40] number_at_index = a[3] except: print(“Error: Index out of range.”) else: print(“The number at index a[3] is: “, number_at_index) |
Python Program 02 |
”’ __author__ = Ms. Samavi Salman __copyright__= Copyright (C) 2020 Ms. Samavi Salman __license__ = Public Domain __version__ = 1.0 ”’
”’ The main purpose of this Program is to take an Integer Variable as input from the User, display whether it’s a Leap Year or not on the Output Screen ”’
try: year = int(input(“Enter a Year: “)) leap_year = year % 4 == 0 if (leap_year): print(“This is a leap year”) except ValueError: print(“Invalid Input. Please enter an Integer value.”) else: print(“This is not a leap year”) |
Python Program 03 |
”’ __author__ = Ms. Samavi Salman __copyright__= Copyright (C) 2020 Ms. Samavi Salman __license__ = Public Domain __version__ = 1.0 ”’
”’ The main purpose of this Program is to take an Integer Variable as input from the User, display whether it’s an Even Number or Odd Number on the Output Screen ”’
try: number = int(input(“Enter a number: “)) if(number % 2 == 0): print(number, “is an Even number”) except: print(“Invalid Input. Strings are not allowed. Please enter an Integer value.”) else: print(number, “is an Odd number”) |
Python Program 04 |
”’ __author__ = Ms. Samavi Salman __copyright__= Copyright (C) 2020 Ms. Samavi Salman __license__ = Public Domain __version__ = 1.0 ”’
”’ The main purpose of this Program is to take an Integer Variable as input from the User and display Square of Variable on the Output Screen ”’
try: number = int(input(“Enter an integer number: “)) if(number > 0) square = number * number print(square) except: print(“Invalid Input. Please enter an integer number. “) else: print(“You have entered a negative number”) |
- Note
- Your answer should be
- Well justified
- Your answer should be
- Questions
- Which Exception Handler is being used in the Python Programs to handle Exceptions?
- Which Python Programs generated Exception(s)?
- Where was Exception(s) (Runtime Error(s)) Generated in the Python Programs?
- Where was Exception(s) (Runtime Error(s)) Handled in the Python Program?
- What was the main reason for Exception(s) (Runtime Error(s))
- Write down your Findings / Conclusions after running the Python Programs?
Your Turn Task 1
- Task
- Write Five Python Programs using try /except /else Exception Handler and answer the questions given below
- Note
- Your answer should be
- Well justified
- Your answer should be
- Questions
- Which Exception Handler is being used in the Python Programs to handle Exceptions?
- Which Python Programs generated Exception(s)?
- Where was Exception(s) (Runtime Error(s)) Generated in the Python Programs?
- Where was Exception(s) (Runtime Error(s)) Handled in the Python Program?
- What was the main reason for Exception(s) (Runtime Error(s))
- Write down your Findings / Conclusions after running the Python Programs?
Exception Handling using try / except / finally
- Exception Handling using try / except / finally
- Definition
- When we handle Exception(s) (Runtime Error(s)) using try / except / finally
- try Block lets you Test a Block of Code for Exception(s) (or Runtime Error(s)) and
- except Block lets you handle the Exceptions (or Runtime Error(s)) that was raised in the try Block
- finally lets you execute Code, regardless of the result of the try and except Blocks of Code
- Note
- In Exception Handling using try / except / finally, you can have
- one or more except Statements
- In Exception Handling using try / except / finally, you can have
- Purpose
- The main purpose of try / except / finally Exception Handler is to
- add more flexibility to the try / except Exception Handler by executing Code, regardless of the result of the try and except Blocks of Code
- The main purpose of try / except / finally Exception Handler is to
- Importance
- try / except / finally helps you to handle Exception(s) (Runtime Error(s)) that were not perceived by a Programmer when he was writing the Code
- try / except / finally provides you more flexibility by executing Code, regardless of the result of the try and except Blocks of Code
- try / except / finally is one of the common and popular approach to handle Exception(s) (Runtime Error(s)) in Python Program
- Applications
- try / except / finally helps a Programmer to enable flow control
- Suitable to Use
- try / except / finally is more suitable to use when we want to execute a Code, regardless of the result of the try and except Blocks of Code
- A Programmer should use Exception Handlers in all Blocks of Codes
- Syntax - try / except / finally
try:
# Python Statements in try Block
except:
# Executed when Error occurs in Code inside try Block
except:
# Executed when Error occurs in Code inside try Block
finally:
# Executed regardless of Error in try / except Block
- Example 1 – Exception Handling using try / except / finally
- Given
- Write a Python Program which display the value of an Integer Variable on the Output Screen
- Task
- Your Code should have the ability to properly handle Exception(s) (Runtime Errors(s))
'''
__author__ = Ms. Samavi Salman
__copyright__= Copyright (C) 2020 Ms. Samavi Salman
__license__ = Public Domain
__version__ = 1.0
'''
'''
The main purpose of this Program is to print the value of an Integer Variable on Output Screen
'''
'''
In the following Code, Exception occurs because Variable 'number' is not defined
'''
try:
print(number6)
except:
print("Error: Variable is not defined. Please declare the variable and then use it. ")
finally:
print("Alert: The execution of the program is completed ")
Error: Variable is not defined. Please declare the variable and then use it.
Alert: The execution of the program is completed
- Remarks
- I used try / except / finally for Exception Handling
- Will Program Generate Exception(s) (Runtime Error(s))?
- Yes
- Where was Exception(s) (Runtime Error(s)) Generated in the Python Program?
- In try Block of Code
- Where was Exception(s) (Runtime Error(s)) Handled in the Python Program?
- In except Block of Code
- Reason for Exception(s) (Runtime Error(s))
- The try block will generate an Exception (Runtime Error), because
- Variable (called number) is not defined in the Python Program
- The try block will generate an Exception (Runtime Error), because
- Conclusion
- Proper Exception Handling improves the overall quality of the Python Program
- Example 2 – Exception Handling using try / except / finally
- Given
- Write a Python Program which display division of two Integer Variables on the Output Screen
- Task
- Your Code should have the ability to properly handle Exception(s) (Runtime Errors(s))
'''
__author__ = Ms. Samavi Salman
__copyright__= Copyright (C) 2020 Ms. Samavi Salman
__license__ = Public Domain
__version__ = 1.0
'''
'''
The main purpose of this Program is to display division of two Integer Variables on the Output Screen
'''
'''
In the following Program, Exception occurs because Variable ‘number1’ is divided by Variable ‘number2’ i.e. Zero
'''
try:
number1 = 10
number2 = 0
result = number1 / number2
print(result)
except:
print("Error: Invalid Division. Number is divided by Zero.")
finally:
print("Alert: The execution of the program is completed")
Error: Invalid Division. Number is divided by Zero.
Alert: The execution of the program is completed
- Remarks
- I used try / except for Exception Handling
- Will Program Generate an Exception(s) (Runtime Error(s))?
- Yes
- Where was Exception(s) (Runtime Error(s)) Generated in the Python Program?
- In try Block of Code
- Where was Exception(s) (Runtime Error(s)) Handled in the Program?
- In except Block of Code
- Reason for Exception(s) (Runtime Error(s))
- The try block will generate an Exception (Runtime Error), because
- Variable (called number1) is divided by Zero which is Invalid
- The try block will generate an Exception (Runtime Error), because
- Conclusion
- Proper Exception Handling improves the overall quality of the Python Program
- Example 3 – Exception Handling using try / except / finally
- Given
- Write a Python Program which display the sum of two Integer Variables on the Output Screen
- Task
- Your Code should have the ability to properly handle Exception(s) (Runtime Error(s))
'''
__author__ = Ms. Samavi Salman
__copyright__= Copyright (C) 2020 Ms. Samavi Salman
__license__ = Public Domain
__version__ = 1.0
'''
'''
The main purpose of this program is to display the sum of two Integer Variables on the Output Screen
'''
'''
In the following Program, Exception occurs because we are adding INTEGER (value of Variable 'number1') and STRING (value of Variable 'number2')
'''
try:
number1 = 8
number2 = '5'
sum = number1 + number2
print(sum)
except:
print("Error: Invalid Addition. Integer cannot be added with String.")
finally:
print("Alert: The execution of the program is completed")
Error: Invalid Addition. Integer cannot be added with String.
Alert: The execution of the program is completed
- Remarks
- I used try / except for Exception Handling
- Will Program Generate an Exception (Runtime Errors)?
- Yes
- Where was Exception(s) (Runtime Error(s)) Generated in the Python Program?
- In try Block of Code
- Where was Exception(s) (Runtime Error(s)) Handled in the Python Program?
- In except Block of Code
- Reason for Exception(s) (Runtime Error(s))
- The try block will generate an Exception (Runtime Error), because
- Variable (called number1) is an Integer and Variable (called number2) is a String
- Integer and String cannot be added
- The try block will generate an Exception (Runtime Error), because
- Conclusion
- Proper Exception Handling improves the overall quality of the Python Program
- Example 4 – Exception Handling using try / except / finally
- Given
- Write a Python Program which display a List of Integer elements along with their indices on the Output Screen
- Task
- Your Code should have the ability to properly handle Exception(s) (Runtime Error(s)) Code
'''
__author__ = Ms. Samavi Salman
__copyright__= Copyright (C) 2020 Ms. Samavi Salman
__license__ = Public Domain
__version__ = 1.0
'''
'''
The main purpose of this Program is to display a List of Integer elements along with their indices on the Output Screen
'''
'''
In the following Program, Exception occurs because Variable (called numbers) contains List of element whose last element is at index 2
'''
try:
numbers = [1, 2, 3]
print("Second Element of List is: ", numbers[1])
print("Last Element of the List is: ", number[3])
except:
print("Error: Invalid Index Number. The last element of List is at index 2")
finally:
print("Alert: The execution of the program is completed")
Second Element of List is: 2
Error: Invalid Index Number. The last element of List is at index 2
Alert: The execution of the program is completed
- Remarks
- I used try / except for Exception Handling
- Will Program Generate an Exception(s) (Runtime Error(s))?
- Yes
- Where was Exception(s) (Runtime Error(s)) Generated in the Python Program?
- In try Block of Code
- Where was Exception(s) (Runtime Error(s) Handled in the Python Program?
- In except Block of Code
- Reason for Exception(s) (Runtime Error(s))
- The try block will generate an Exception (Runtime Error), because
- Variable (called number) contains List element with index number i.e. 2
- The try block will generate an Exception (Runtime Error), because
- Conclusion
- Proper Exception Handling improves the overall quality of the Python Program
- Example 5 – Exception Handling using try / except / finally
- Given
- Write a Python Program which divides 1 by each element of a List and display the results on the Output Screen
- Task
- Your Code should have the ability to properly handle Exception(s) (Runtime Error(s))
'''
__author__ = Ms. Samavi Salman
__copyright__= Copyright (C) 2020 Ms. Samavi Salman
__license__ = Public Domain
__version__ = 1.0
'''
'''
The main purpose of this Program is to divides 1 by each element of a List and display the results on the Output Screen
'''
'''
In the following Program, Exception occurs because Variable (called numbers) contains List of elements whose last element is a String
'''
try:
numbers = [1, 2, 'a']
for number in numbers:
divide = 1 / int(number)
print("1 /", number, "=", divide)
except:
print("Error: Invalid Division. Integer Variable is divided by a String")
finally:
print("Alert: The execution of the program is completed")
1 / 1 = 1.0
1 / 2 = 0.5
Error: Invalid Division. Integer Variable is divided by a String
Alert: The execution of the program is completed
- Remarks
- I used try / except for Exception Handling
- Will Program Generate an Exception(s) (Runtime Error(s))?
- Yes
- Where was Exception(s) (Runtime Error(s)) Generated in the Python Program?
- In try Block of Code
- Where was Exception(s) (Runtime Error(s)) Handled in the Python Program?
- In except Block of Code
- Reason for Exception(s) (Runtime Error(s))
- The try block will generate an Exception (Runtime Error), because
- Variable (called numbers) contains List whose last element is a String i.e. ’a’
- The try block will generate an Exception (Runtime Error), because
- Conclusion
- Proper Exception Handling improves the overall quality of the Python Program
- Example 6 – Exception Handling using try / except / finally
- Given
- Write a Python Program which display the alphabets from String Variable on the Output Screen
- Task
- Your Code should have the ability to properly handle Exception(s) (Runtime Error(s))
'''
__author__ = Ms. Samavi Salman
__copyright__= Copyright (C) 2020 Ms. Samavi Salman
__license__ = Public Domain
__version__ = 1.0
'''
'''
The main purpose of this Program is to display the alphabets from String Variable on the Output Screen
'''
'''
In the following Program, no Exception occurs because Variable (called 'message') contains the specified alphabet i.e. 'r'
'''
# Use of break statement inside the loop
try:
message = "Inspiration"
for alphabet in message:
if alphabet == "r":
break
print(alphabet)
except:
print("Error: The message doesn’t contain alphabet 'r'")
finally:
print("Alert: The execution of the program is completed")
I
n
s
p
i
Alert: The execution of the program is completed
- Remarks
- I used try / except for Exception Handling
- Will Program Generate an Exception(s) (Runtime Error(s))?
- No
- Where was Exception(s) (Runtime Error(s)) Generated in the Python Program?
- In try Block of Code
- Where was Exception(s) (Runtime Error(s)) Handled in the Python Program?
- In except Block of Code
- Reason for Exception(s) (Runtime Error(s))
- The try block will not generate any Exception (Runtime Error), because
- Variable (called message) contains alphabet i.e. ‘r’ in the String
- The try block will not generate any Exception (Runtime Error), because
- Conclusion
- Proper Exception Handling improves the overall quality of the Python Program
- Example 7 – Exception Handling using try / except / finally
- Given
- Write a Python Program which display the alphabets from String on the Output Screen
- Task
- Your Code should have the ability to properly handle Exception(s) (Runtime Error(s))
'''
__author__ = Ms. Samavi Salman
__copyright__= Copyright (C) 2020 Ms. Samavi Salman
__license__ = Public Domain
__version__ = 1.0
'''
'''
The main purpose of this Program is to display the alphabets from String on the Output Screen
'''
'''
In the following Program, no Exception occurs because Variable (called 'message') contains the specified alphabet i.e. 'e'
'''
try:
message = "Believe"
for alphabet in message:
if alphabet == "e":
continue
print(alphabet)
except:
print("Error: The message doesn’t contain alphabet 'e'")
finally:
print("Alert: The execution of the program is completed")
B
l
i
v
Alert: The execution of the program is completed
- Remarks
- I used try / except for Exception Handling
- Will Program Generate an Exception(s) (Runtime Error(s))?
- No
- Where was Exception(s) (Runtime Error(s)) Generated in the Python Program?
- In try Block of Code
- Where was Exception(s) (Runtime Error(s)) Handled in the Python Program?
- In except Block of Code
- Reason for Exception(s) (Runtime Error(s))
- The try block will not generate any Exception (Runtime Error), because
- Variable (called message) contains alphabet i.e. ‘e’ in the String
- The try block will not generate any Exception (Runtime Error), because
- Conclusion
- Proper Exception Handling improves the overall quality of the Python Program
TODO and Your Turn
TODO Tasks
- Task
- Write Five Python Programs using try /except / finally Exception Handler and answer the questions given below
Python Program 01 |
”’ __author__ = Ms. Samavi Salman __copyright__= Copyright (C) 2020 Ms. Samavi Salman __license__ = Public Domain __version__ = 1.0 ”’
”’ The main purpose of this Program is to display the alphabets from String on the Output Screen ”’
try: message = “Dreams” for alphabet in message: if alphabet == “a”: break print(alphabet) except: print(“Error: The message doesn’t contain alphabet ‘e'”) finally: print(“Alert: The execution of the program is completed”) |
Python Program 02 |
”’ __author__ = Ms. Samavi Salman __copyright__= Copyright (C) 2020 Ms. Samavi Salman __license__ = Public Domain __version__ = 1.0 ”’
”’ The main purpose of this Program is to display the alphabets from String on the Output Screen ”’
try: message = “Care” for alphabet in message: if alphabet == “r”: continue print(alphabet) except: print(“Error: The message doesn’t contain alphabet ‘e'”) finally: print(“Alert: The execution of the program is completed”) |
Python Program 03 |
”’ __author__ = Ms. Samavi Salman __copyright__= Copyright (C) 2020 Ms. Samavi Salman __license__ = Public Domain __version__ = 1.0 ”’
”’ The main purpose of this Program is to take an Integer Variable as input from User, and display whether it’s an Even Number or Odd Number on the Output Screen ”’
try: num = int(input(“Enter a number: “))
if num % 2 == 0: print(num, “is Even Number”) else: print(num, “is Odd Number”) finally: print(“Alert: The execution of the program is completed”) |
Python Program 04 |
”’ __author__ = Ms. Samavi Salman __copyright__= Copyright (C) 2020 Ms. Samavi Salman __license__ = Public Domain __version__ = 1.0 ”’
”’ The main purpose of the Program is to take display a List of Integer elements at specific index on Output Screen ”’
try: number = ‘100’ print(number[0]) except: print(“Error: Invalid number. Variable is an Integer not a List”) finally: print(“Alert: The execution of the program is completed”) |
- Note
- Your answer should be
- Well justified
- Your answer should be
- Questions
- Which Exception Handler is being used in the Python Programs to handle Exceptions?
- Which Python Programs generated Exception(s)?
- Where was Exception(s) (Runtime Error(s)) Generated in the Python Programs?
- Where was Exception(s) (Runtime Error(s)) Handled in the Python Program?
- What was the main reason for Exception(s) (Runtime Error(s))
- Write down your Findings / Conclusions after running the Python Programs?
Your Turn Tasks
- Task
- Consider the following three Python Programs and answer the following questions
- Note
- Your answer should be
- Well justified
- Your answer should be
- Questions
- Which Exception Handler is being used in the Python Programs to handle Exceptions?
- Which Python Programs generated Exception(s)?
- Where was Exception(s) (Runtime Error(s)) Generated in the Python Programs?
- Where was Exception(s) (Runtime Error(s)) Handled in the Python Program?
- What was the main reason for Exception(s) (Runtime Error(s))
- Write down your Findings / Conclusions after running the Python Programs?
Exception Handling using raise
- Raising and Exception
- Definition
- A Programmer can choose to Throw (or raise) a specific Exception using raise Keyword
- Important Note
- Mostly raise Exception is followed by an
- If Statement
- When an Exception is raised using the raise Keyword
- no further Python Statements in the Current Block of Code are executed
- Mostly raise Exception is followed by an
- Purpose
- The main purpose of raise is to give liberty to a Programmer to
- Choose and
- Throw an Exception himself
- The main purpose of raise is to give liberty to a Programmer to
- Importance
- raise allows you to
- throw an Exception of your choice
- raise allows you to
- Applications
- raise allows us to generate a variety of Exceptions to improve the overall quality of the Code
- Suitable to Use
- raise is suitable to use when you want to
- add very specific constraints in your Code
- raise is suitable to use when you want to
- Most Common raise Exceptions
- Some of the most common raise Exception are
- TypeError
- ZeroDivisionError
- SyntaxError
- IndentationError
- ValueError
- SyntaxError
- RuntimeError
- NameError
- ArithmeticError
- Some of the most common raise Exception are
- Syntax - raise
raise Exception(Message)
- Example 1 – raise
- Given
- Write a Python Program which display whether the Integer is greater than Zero or not on Output Screen
- Task
- Your Code should have the ability to properly handle Exception(s) (Runtime Errors(s))
'''
__author__ = Ms. Samavi Salman
__copyright__= Copyright (C) 2020 Ms. Samavi Salman
__license__ = Public Domain
__version__ = 1.0
'''
'''
The main purpose of this Program is to display whether the Integer is greater than Zero or not on Output Screen
'''
'''
In the following Program, Exception occurs because Variable 'number' is less than 0
'''
number = -20
if number < 0:
raise Exception("Sorry! Number cannot be less than ZERO")
---------------------------------------------------------------------------
Exception Traceback (most recent call last)
in
17
18 if number < 0:
---> 19 raise Exception("Sorry! Number cannot be less than ZERO")
Exception: Sorry! Number cannot be less than ZERO
- Remarks
- I used try / except for Exception Handling
- Will Program Generate an Exception(s) (Runtime Error(s))?
- Yes
- Where was Exception(s) (Runtime Error(s)) Generated in the Python Program?
- In try Block of Code
- Where was Exception(s) (Runtime Error(s)) Handled in the Program?
- In except Block of Code
- Reason for Exception(s) (Runtime Error(s))
- The try block will generate an Exception (Runtime Error), because
- Variable (called number) is less than Zero
- The try block will generate an Exception (Runtime Error), because
- Conclusion
- Proper Exception Handling improves the overall quality of the Python Program
- Example 2 – raise
- Given
- Write a Python Program is to print Integer Variable on the Output Screen
- Task
- Your Code should have the ability to properly handle Exception(s) (Runtime Errors(s))
'''
__author__ = Ms. Samavi Salman
__copyright__= Copyright (C) 2020 Ms. Samavi Salman
__license__ = Public Domain
__version__ = 1.0
'''
'''
The main purpose of this Program is to print Integer Variable on the Output Screen
'''
'''
In the following Program, Exception occurs because Variable "message" is initialized with a String in the Python Program
'''
message = "Offer Prayers 5 times a day"
if not type(message) is int:
raise TypeError("Sorry! Only Integer values are acceptable.")
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
in
17
18 if not type(message) is int:
---> 19 raise TypeError("Sorry! Only Integer values are acceptable.")
TypeError: Sorry! Only Integer values are acceptable.
- Remarks
- I used try / except for Exception Handling
- Will Program Generate Exception(s) (Runtime Error(s))?
- Yes
- Where was Exception(s) (Runtime Error(s)) Generated in the Python Program?
- In try Block of Code
- Where was Exception(s) (Runtime Error(s)) Handled in the Python Program?
- In except Block of Code
- Reason for Exception(s) (Runtime Error(s))
- The try block will generate an Exception (Runtime Error), because
- Variable (called message) is initialized with a String in the Python Program
- The try block will generate an Exception (Runtime Error), because
- Conclusion
- Proper Exception Handling improves the overall quality of the Python Program
- Example 3 – raise
- Given
- Write a Python Program which display two Positive Integers on the Output Screen
- Task
- Your Code should have the ability to properly handle Exception(s) (Runtime Errors(s))
'''
__author__ = Ms. Samavi Salman
__copyright__= Copyright (C) 2020 Ms. Samavi Salman
__license__ = Public Domain
__version__ = 1.0
'''
'''
The main purpose of this Program is to display two Positive Integers on the Output Screen
'''
'''
In the following Program, Exception occurs because Variable 'number1' and 'number2' both are Negative Integers
'''
number1 = -10
number2 = -9
if number1 < 0 or number2 < 0:
raise ZeroDivisionError("Sorry! Number cannot be less than Zero.")
---------------------------------------------------------------------------
ZeroDivisionError Traceback (most recent call last)
in
18
19 if number1 < 0 or number2 < 0:
---> 20 raise ZeroDivisionError("Sorry! Number cannot be less than Zero.")
ZeroDivisionError: Sorry! Number cannot be less than Zero.
- Remarks
- I used try / except for Exception Handling
- Will Program Generate an Exception(s) (Runtime Error(s))?
- Yes
- Where was Exception(s) (Runtime Error(s)) Generated in the Python Program?
- In try Block of Code
- Where was Exception(s) (Runtime Error(s)) Handled in the Program?
- In except Block of Code
- Reason for Exception(s) (Runtime Error(s))
- The try block will generate an Exception (Runtime Error), because
- Variable (called number1 and number2) are less than Zero i.e. Negative Integers
- The try block will generate an Exception (Runtime Error), because
- Conclusion
- Proper Exception Handling improves the overall quality of the Python Program
- Jupyter Notebook File
- For Code of all the Examples given above
- See examples-exception-handling.ipynb File in Data and Code
TODO and Your Turn
TODO Task 1
- Task
- Consider the following three Python Programs and answer the following questions
Python Program 01 |
”’ __author__ = Ms. Samavi Salman __copyright__= Copyright (C) 2020 Ms. Samavi Salman __license__ = Public Domain __version__ = 1.0 ”’
”’ The main purpose of this Program is to display a String on the Output Screen ”’
string = “ The harder you work for something, the greater you’ll feel when you achieve it”
if(string == “harder”): raise Exception(“Error: Invalid String”) |
Python Program 02 |
”’ __author__ = Ms. Samavi Salman __copyright__= Copyright (C) 2020 Ms. Samavi Salman __license__ = Public Domain __version__ = 1.0 ”’
”’ The main purpose of this Program is to take Positive Integer Variable as input from User and display whether it’s a Positive Number or not on the Output Screen ”’
number = int(input(“Enter a positive number: “))
if number < 0: raise Exception(“Error: Invalid Input. Please enter Positive Integer”) |
Python Program 03 |
”’ __author__ = Ms. Samavi Salman __copyright__= Copyright (C) 2020 Ms. Samavi Salman __license__ = Public Domain __version__ = 1.0 ”’
”’ The main purpose of this Program is to take two Integer Variables as input from User and display the division on the Output Screen ”’
try: number1 = int(input(“Enter first number: “)) number2 = int(input(“Enter second number: “)) if(number2 == 0): raise ArithmeticError else: print(“number1/number2 = “, number1/number2) except ArithmeticError: print(“Error: Invalid Input. Number cannot be divided by Zero”) |
- Note
- Your answer should be
- Well justified
- Your answer should be
- Questions
- Which Exception Handler is being used in the Python Programs to handle Exceptions?
- Which Python Programs generated Exception(s)?
- Where was Exception(s) (Runtime Error(s)) Generated in the Python Programs?
- Where was Exception(s) (Runtime Error(s)) Handled in the Python Program?
- What was the main reason for Exception(s) (Runtime Error(s))
- Write down your Findings / Conclusions after running the Python Programs?
Your Turn Task 1
- Task
- Write Five Python Programs using raise Exception Handler and answer the questions given below
- Note
- Your answer should be
- Well justified
- Your answer should be
- Questions
- Which Exception Handler is being used in the Python Programs to handle Exceptions?
- Which Python Programs generated Exception(s)?
- Where was Exception(s) (Runtime Error(s)) Generated in the Python Programs?
- Where was Exception(s) (Runtime Error(s)) Handled in the Python Program?
- What was the main reason for Exception(s) (Runtime Error(s))
- Write down your Findings / Conclusions after running the Python Programs?
Chapter Summary
- Chapter Summary
In this Chapter, I presented the following main concepts:
- Exception
- In a Programming Language, an Exception is defined as an unplanned event (or Runtime Error), which occurs during the execution of a Program and it disrupts the normal flow of the Program’s instructions
- Exception Handler
- An Exception Handler is a piece of Code that stimulates what a Program will do when an Exception (Runtime Errors) occurs in a Program
- Exception Handling
- In Programming Languages, Exception Handling is defined as the mechanism of handling Exception(s) (Runtime Errors) (or Runtime Error(s))
- Types of Exceptions in Python
- Built in Exceptions
- User Defined Exceptions
- Built in Exceptions
- A Built-in Exception is defined as an Exception which is generated either by an Interpreter or Built-in Function
- User Defined Exception
- A User Defined Exception is an Exception which is written by a Programmer
- Exception Handling using try / except
- When we handle Exception(s) (Runtime Error(s)) using try / except
- try Block lets you Test a Block of Code for Exception(s) (Runtime Error(s)) and
- except Block lets you handle the Exception(s) (or Runtime Error(s)) that was raised in the try Block
- When we handle Exception(s) (Runtime Error(s)) using try / except
- Exception Handling using try / except / else
- When we handle Exception(s) (Runtime Error(s)) using try / except / else
- try Block lets you Test a Block of Code for Exception(s) (or Runtime Error(s)) and
- except Block lets you handle the Exception (or Runtime Error) that was raised in the try Block
- else Block of Code will be executed only if no Exception(s) is generated in try Block of Code
- When we handle Exception(s) (Runtime Error(s)) using try / except / else
- Exception Handling using try / except / finally
- When we handle Exception(s) (Runtime Error(s)) using try / except / finally
- try Block lets you Test a Block of Code for Exception(s) (or Runtime Error(s)) and
- except Block lets you handle the Exceptions (or Runtime Error(s)) that was raised in the try Block
- finally lets you execute Code, regardless of the result of the try and except Blocks of Code
- When we handle Exception(s) (Runtime Error(s)) using try / except / finally
- Exception Handling using raise
- A Programmer can choose to Throw (or raise) a specific Exception using raise Keyword
In Next Chapter
- In Next Chapter
- In Sha Allah, in the next Chapter, I will present a detailed discussion on
- Software Testing