In python, try except statements are used to handle exceptions in the code, when a error occurs it will break the program to prevent it and to log the error, this will be really helpful when running the code in production where it might end up with multiple error of different cases.
Python support different exception capture method, let see the syntax of the try statement.
try:
# try code block
pass
except:
print("except")
else:
print("else")
finally:
print("finally")
Python try and except block
try section where the main logic of the code will be written.
except block is used to capture the error occurred in try block
try:
x = 1 / 0
except:
print("except")
Output:
except
capture exception error
try:
x = 1 / 0
except Exception as e:
print("except:", e)
Output:
except: division by zero
else block
We already knew else is used in if statement, it will be executed when if statement is not True. Same kind logic applied here, when there is not exception occurred then the else block will executed after completing the try block code.
try:
x = 1 / 5
except Exception as e:
print("except:", e)
else:
print("else")
Output:
else
finally block
finally block will always execute regardless of the exception occurrence
try:
x = 1 / 5
except Exception as e:
print("except:", e)
else:
print("else")
finally:
print("finally")
Output:
else
finally
Capture Specific Exception in Python
Python support different exception types such as OSError, ValueError, ZeroDivisionError, etc
try:
x = 1 / 0
except OSError as e:
print("OSError:", e)
except ValueError as e:
print("ValueError:", e)
except ZeroDivisionError as e:
print("ZeroDivisionError:", e)
except Exception as e:
print("except:", e)
Output:
ZeroDivisionError: division by zero
since this error is occurred because the value is divided by zero it will be captured in ZeroDivisionError
Python Catch multiple exceptions in one line
try:
x = 1 / 0
except (OSError, ValueError, ZeroDivisionError) as e:
print("ERROR:", e)
except Exception as e:
print("except:", e)
Output:
ERROR: division by zero
Note: multiple exception types must be parenthesized
you can ask then what is the use of next except block, suppose we don't what kind of error will occurs then this block can be used to capture all type of exceptions.
try:
print(y)
except (OSError, ValueError, ZeroDivisionError) as e:
print("ERROR:", e)
except Exception as e:
print("except:", e)
Output:
except: name 'y' is not defined
Explore Other Related Articles
Python classes and objects tutorial
Python Recursion Function Tutorial
Python Lambda Function Tutorial
Python If, If-Else Statements Tutorial
Python Function Tutorial
Python break and continue tutorial
Top comments (0)