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
Nesta página do site você pode assistir ao vídeo on-line Exception Handling, Try , Except - LECTURE 9 | Introduction to Python | Python for Beginners duração hora minuto segundo em boa qualidade , que foi baixado pelo usuário Learn21 Academy 14 Dezembro 2020, compartilhe o link com seus amigos e conhecidos, no youtube este vídeo já foi visto 35 vezes e gostou 3 espectadores. Boa visualização!