How to use try and except in a funtion?
How to use try and except in a funtion?
84
20-Jul-2023
Updated on 20-Jul-2023
Aryan Kumar
20-Jul-2023Sure, here is how you can use try and except in a function:
Python
In this example, the
divide_numbers()
function takes two numbers as input and divides them. If the denominator is zero, theZeroDivisionError
exception is raised. Thetry
/except
block catches the exception and prints a message to the user. Theelse
block is executed if the exception is not raised. In this case, theelse
block returns the result of the division operation.Here is a breakdown of how the
try
/except
block works:try
keyword indicates the beginning of a block of code that may throw an exception.except
keyword is followed by the name of the exception that you want to catch. In this case, we are catching theZeroDivisionError
exception.except
block will be executed if the exception is raised. In this case, the code prints a message to the user.else
keyword is followed by a block of code that will be executed if the exception is not raised. In this case, the code returns the result of the division operation.