Lesson - 42 : Python3 - Python Exception Handling : Exception, Hierarchy, Handling, Different blocks

Опубликовано: 08 Октябрь 2024
на канале: Sada Learning Hub
85
4

**************************************************
Python Core PlayList :    • Lesson - 01 : Python3 - What is python  
Python Advanced PlayList :    • Lesson - 46 : Python Advanced - Pytho...  
**************************************************
Python Exception Handling : What is an exception:
Exception handling enables you handle errors gracefully and do something meaningful about it. Like display a message to user if intended file not found. Python handles exception using try.. except ..  block.

Syntax :
try:
    write some code
    that might throw exception
except <ExceptionType>:
    Exception handler, alert the user

As you can see in try block you need to write code that might throw an exception. When exception occurs code in the try block is skipped. If there exist a matching exception type inexcept  clause then it’s handler is executed.
try:
    f = open('somefile.txt', 'r')
    print(f.read())
    f.close()
except IOError:
    print('file not found')

Python Exception Handling : How to handle the exception:
Exception handling enables you handle errors gracefully and do something meaningful about it. Like display a message to user if intended file not found. Python handles exception using try.. except ..  block.

As you can see in try block you need to write code that might throw an exception. When exception occurs code in the try block is skipped. If there exist a matching exception type inexcept  clause then it’s handler is executed.
try:
    f = open('somefile.txt', 'r')
    print(f.read())
    f.close()
except IOError:
    print('file not found')

1. First statement between try  and except  block are executed.
2. If no exception occurs then code under except  clause will be skipped.
3. If file don’t exists then exception will be raised and the rest of the code in the try  block will be skipped
4. When exceptions occurs, if the exception type matches exception name after except  keyword, then the code in that except  clause is executed.

Sample Projects : https://github.com/SadaLearningHub1/P...