Exception Handling, Try , Except - LECTURE 9 | Introduction to Python | Python for Beginners

Publié le: 14 décembre 2020
sur la chaîne: Learn21 Academy
35
3

Live Python course: https://learn21.in/course/python-for-...
For one-to-one guidance, you can email at uplabs.in@gmail.com.

Exception handling Python
Concept Try/Except Exception Types Finally/Else Clause Writing custom Exceptions
What is an Exception?
Anomalous or exceptional conditions requiring special processing - during

the execution of a program.
• • •
Example: dividing by zero, query an id which doesn’t exist, the file doesn’t exist An exception breaks the normal flow of execution
Exception handling is required to avoid the program from breaking and providing clues to users and developers

Exception Handling
def divide(a, b):
return a/b
def divide(a, b): try:
result = a/b except:
result = “something went wrong” return result
• The execution doesn’t stop if the exception is handled

Handling Exception Type
def divide(a, b): try:
result = a/b
except ZeroDivisionError:
result = “can’t divide by 0” except TypeError:
result = “type should be integers” return result
Common Python built-in exceptions:
`ValueError` — Raised when a function receives an argument of the correct type but an inappropriate value.
`TypeError` — Raised when an operation or function is applied to an object of inappropriate type.
`KeyError` — Raised when a mapping (dictionary) key is not found in the set of existing keys.
`IndexError` - Raised when a sequence subscript is out of range.

Finally & else clause
def divide(a, b): try:
result = a/b
except ZeroDivisionError:
result = “can’t divide by 0” else:
Executed if no exception occurs
result = “0”
except Exception as e:
result = str(e) finally:
Executed always
print (“process over”) return result
Manually raise exception
raise NameError(“this is a problem”)

Writing Custom Exceptions
Create and raise Custom exception 'InputError' class InputError(Exception):
pass
raise InputError('Custom exception')
Output:
Traceback (most recent call last): # File "stdin", line 4, in module # InputError: Custom exception

▶️ You Can Find Us On:
Website - https://learn21.in/
Telegram channel: https://t.me/learn21_in
Twitter -   / 21_learn  
LinkedIn -   / learn-21  

#python #programming #programmers #github #coding #exceptionhandling #exceptionpython #developer #coder


Sur cette page du site, vous pouvez voir la vidéo en ligne Exception Handling, Try , Except - LECTURE 9 | Introduction to Python | Python for Beginners durée heure minute seconde en bonne qualité , qui a été Téléchargé par l'utilisateur Learn21 Academy 14 décembre 2020, Partagez le lien avec vos amis et connaissances, sur youtube cette vidéo a déjà été regardée 35 fois et il a aimé 3 téléspectateurs. Bon visionnage!