Thanks to visit codestin.com
Credit goes to www.tutorialsteacher.com

Tutorialsteacher

Follow Us

Articles
  • C#
  • C# OOP
  • ASP.NET Core
  • ASP.NET MVC
  • LINQ
  • Inversion of Control (IoC)
  • Web API
  • JavaScript
  • TypeScript
  • jQuery
  • Angular 11
  • Node.js
  • D3.js
  • Sass
  • Python
  • Go lang
  • HTTPS (SSL)
  • Regex
  • SQL
  • SQL Server
  • PostgreSQL
  • MongoDB
  • Python - Get Started
  • What is Python?
  • Where to use Python?
  • Python Version History
  • Install Python
  • Python - Shell/REPL
  • Python IDLE
  • Python Editors
  • Python Syntax
  • Python Keywords
  • Python Variables
  • Python Data Types
  • Number
  • String
  • List
  • Tuple
  • Set
  • Dictionary
  • Python Operators
  • Python Conditions - if, elif
  • Python While Loop
  • Python For Loop
  • User Defined Functions
  • Lambda Functions
  • Variable Scope
  • Python Modules
  • Module Attributes
  • Python Packages
  • Python PIP
  • __main__, __name__
  • Python Built-in Modules
  • OS Module
  • Sys Module
  • Math Module
  • Statistics Module
  • Collections Module
  • Random Module
  • Python Generator Function
  • Python List Comprehension
  • Python Recursion
  • Python Built-in Error Types
  • Python Exception Handling
  • Python Assert Statement
  • Define Class in Python
  • Inheritance in Python
  • Python Access Modifiers
  • Python Decorators
  • @property Decorator
  • @classmethod Decorator
  • @staticmethod Decorator
  • Python Dunder Methods
  • CRUD Operations in Python
  • Python Read, Write Files
  • Regex in Python
  • Create GUI using Tkinter
Entity Framework Extensions - Boost EF Core 9
  Bulk Insert
  Bulk Delete
  Bulk Update
  Bulk Merge

Exception Handling in Python

The cause of an exception is often external to the program itself. For example, an incorrect input, a malfunctioning IO device etc. Because the program abruptly terminates on encountering an exception, it may cause damage to system resources, such as files. Hence, the exceptions should be properly handled so that an abrupt termination of the program is prevented.

Python uses try and except keywords to handle exceptions. Both keywords are followed by indented blocks.

Syntax:
try : #statements in try block except : #executed when error in try block

The try: block contains one or more statements which are likely to encounter an exception. If the statements in this block are executed without an exception, the subsequent except: block is skipped.

If the exception does occur, the program flow is transferred to the except: block. The statements in the except: block are meant to handle the cause of the exception appropriately. For example, returning an appropriate error message.

You can specify the type of exception after the except keyword. The subsequent block will be executed only if the specified exception occurs. There may be multiple except clauses with different exception types in a single try block. If the type of exception doesn't match any of the except blocks, it will remain unhandled and the program will terminate.

The rest of the statements after the except block will continue to be executed, regardless if the exception is encountered or not.

The following example will throw an exception when we try to devide an integer by a string.

Example: try...except blocks
try:
    a=5
    b='0'
    print(a/b)
except:
    print('Some error occurred.')
print("Out of try except blocks.")
Try it
Output
Some error occurred. Out of try except blocks.

You can mention a specific type of exception in front of the except keyword. The subsequent block will be executed only if the specified exception occurs. There may be multiple except clauses with different exception types in a single try block. If the type of exception doesn't match any of the except blocks, it will remain unhandled and the program will terminate.

Example: Catch Specific Error Type
try:
  a=5
  b='0'
  print(a+b)
except TypeError:
  print('TypeError Occurred')
except:
  print('Some error occurred.')  
print ("Out of try except blocks")
Try it
Output
TypeError Occurred Out of try except blocks

The default except: block must come after all the except block that catch specific errors; otherwise Python will raise an error.

Example: Default except: Block
try:
  a=5
  b='0'
  print(a+b)
except:
  print('Some error occurred.')  #except: before other blocks
except TypeError:
  print('TypeError Occurred')
print ("Out of try except blocks")
Try it
Output
File "main.py", line 4 print(a+b) ^ SyntaxError: default 'except:' must be last

As mentioned above, a single try block may have multiple except blocks. The following example uses two except blocks to process two different exception types:

Example: Multiple except Blocks
try:
    a=5
    b=0
    print (a/b)
except TypeError:
    print('Unsupported operation')
except ZeroDivisionError:
    print ('Division by zero not allowed')
except:
  print('Some error occurred.')
print ('Out of try except blocks')
Try it
Output
Division by zero not allowed Out of try except blocks

However, if variable b is set to '0', TypeError will be encountered and processed by corresponding except block.

else and finally

In Python, keywords else and finally can also be used along with the try and except clauses. While the except block is executed if the exception occurs inside the try block, the else block gets processed if the try block is found to be exception free.

Syntax:
try: #statements in try block except: #executed when error in try block else: #executed if try block is error-free finally: #executed irrespective of exception occured or not

The finally block consists of statements which should be processed regardless of an exception occurring in the try block or not. As a consequence, the error-free try block skips the except clause and enters the finally block before going on to execute the rest of the code. If, however, there's an exception in the try block, the appropriate except block will be processed, and the statements in the finally block will be processed before proceeding to the rest of the code.

The example below accepts two numbers from the user and performs their division. It demonstrates the uses of else and finally blocks.

Example: try, except, else, finally blocks
try:
  x,y = 10, 2
  z=x/y
except ZeroDivisionError:
  print("except ZeroDivisionError block")
  print("Division by 0 not accepted")
except:
  print('Some error occurred.')
else:
  print("Division = ", z)
finally:
  print("Executing finally block")
  x=0
  y=0
print ("Out of try, except, else and finally blocks." )
Try it

The first run is a normal case. The out of the else and finally blocks is displayed because the try block is error-free.

Output
Division =  5.0 Executing finally block Out of try, except, else and finally blocks.

The second run is a case of division by zero, hence, the except block and the finally block are executed, but the else block is not executed.

Example: try, except, else, finally blocks
try:
  x,y = 10, 0
  z=x/y
except ZeroDivisionError:
  print("Cannot devide by zero. Try again")
  print("Division by 0 not accepted")
except:
  print('Some error occurred.')
else:
  print("Division = ", z)
finally:
  print("Executing finally block")
  x=0
  y=0
print ("Out of try, except, else and finally blocks." )
Try it
Output
Cannot devide by zero. Try again Division by 0 not accepted Executing finally block Out of try, except, else and finally blocks.

In the third run case, an uncaught exception occurs. The finally block is still executed but the program terminates and does not execute the program after the finally block.

Example: try, except, else, finally blocks
try:
  x,y = 10, "xyz"
  z=x/y
except ZeroDivisionError:
  print("except ZeroDivisionError block")
  print("Division by 0 not accepted")
except:
  print('Error occurred.')
else:
  print("Division = ", z)
finally:
  print("Executing finally block")
  x=0
  y=0
print ("Out of try, except, else and finally blocks." )
Try it
Output
Error occurred. Executing finally block Out of try, except, else and finally blocks.

Typically the finally clause is the ideal place for cleaning up the operations in a process. For example closing a file irrespective of the errors in read/write operations. This will be dealt with in the next chapter.

Raise an Exception

Python also provides the raise keyword to be used in the context of exception handling. It causes an exception to be generated explicitly. Built-in errors are raised implicitly. However, a built-in or custom exception can be forced during execution.

The following code accepts a number from the user. The try block raises a ValueError exception if the number is outside the allowed range.

Example: Raise an Exception
try:
  x,y=100,2
  z=x/2
  if z > 10:
    raise ValueError(z)
except ValueError:
  print(z, "is out of allowed range")
else:
  print(z, "is within the allowed range")
Try it
Output
50.0 is out of allowed range

Here, the raised exception is a ValueError type. However, you can also raise a custom exception type. Visit Python docs to know more about user defined exceptions.

TUTORIALSTEACHER.COM

TutorialsTeacher.com is your authoritative source for comprehensive technologies tutorials, tailored to guide you through mastering various web and other technologies through a step-by-step approach.

Our content helps you to learn technologies easily and quickly for learners of all levels. By accessing this platform, you acknowledge that you have reviewed and consented to abide by our Terms of Use and Privacy Policy, designed to safeguard your experience and privacy rights.

[email protected]

ABOUT USTERMS OF USEPRIVACY POLICY
copywrite-symbol

2024 TutorialsTeacher.com. (v 1.2) All Rights Reserved.