Exception Handling
1. Introduction to Errors and Exceptions
When a Python program runs, two kinds of problems can occur:
Syntax Errors:
Errors caused by incorrect python syntax
detected before execution
Forex: x=10
If x>5 -->missing colon(:)
print (x);
Exceptions
Errors that occur during execution ,even if syntax is correct
Print(10/0) //cause zero division error
2. Types of Errors and Exceptions
Common Built-in Exceptions Cause Example
ZeroDivisionError Divide by zero 10/0
ValueError Invalid value int("abc")
TypeError Wrong data type "10" + 5
NameError Variable not defined print(x)
IndexError Invalid index list[5]
KeyError Missing dictionary key dict["x"]
FileNotFoundError File not found open("a.txt")
3.Exception Handling
Introduction to try and Except
Python uses try-except to handle exceptions gracefully
Basic Syntax Errors
try:
# Code that may cause an error
except:
# Code that runs if errors occurs
Finally: # Optional
# Code that runs on fail or success
Example Handling division by zero
Output:
PS C:\Users\Administrator\Desktop\CCIT\PythonCourse\Day25> python app.py
Enter a number:0
Error: There is some problem in your code, Zero Divided By
completed
Task2:
PS C:\Users\Administrator\Desktop\CCIT\PythonCourse\Day25> python app.py
Error: There is some problem in your code: invalid literal for int() with base 10: 'abc'
Task3:
PS C:\Users\Administrator\Desktop\CCIT\PythonCourse\Day25> python app.py
Error:Invalid value supplied
Task4:
PS C:\Users\Administrator\Desktop\CCIT\PythonCourse\Day25> python app.py
Wrong Value supplied By 0
Task5:
PS C:\Users\Administrator\Desktop\CCIT\PythonCourse\Day25> python app.py
Universal Exception block: Wrong Value supplied
Task6:
PS C:\Users\Administrator\Desktop\CCIT\PythonCourse\Day25> python app.py
Universal Exception block: Wrong Value supplied
Execution completed
Exception Hierarchy
All exceptions inherit from BaseException
BaseException
Exception
ValueError
TypeError
ZeroDivisionError
FileNotFoundError
--Thanks
No comments:
Post a Comment