w3resource

Python "except" Block: Catching and Managing Exceptions with Examples

What is the role of the except block and How is it used to catch exceptions?

The "except" block in Python is used to catch and handle exceptions that occur within a corresponding "try" block. When an exception is raised within a "try" block, we can assign a specific code block to execute.

This is how it works:

  • The "except" block follows the "try" block and specifies what exceptions to catch.
  • Whenever an exception occurs in a try block, Python searches for a matching "except" block to handle it.
  • The code inside the "except" block is executed if a match is found.
  • The exception is passed to the "except" block for optional processing.

Example (Single "except" block):

Code:

try:
  num = int(input("Input a number: "))
except ValueError:
  print("Not a valid number!")

Output:

Input a number: abcd
That was not a valid number!

Input a number: 15

In the example above -

  • In this case, ValueError will be caught and handled by printing an error message.
  • Multiple "except" blocks can be used to catch different exceptions.
  • All exceptions will be caught by a generic "except" block without specifying an exception.
  • To get error details, use the exception instance in the "except" block.
  • If no exception occurs, the "except" block is skipped.

Here is an example of using multiple "except" blocks in Python to catch different types of exceptions:

Code:

try:
  x = int(input("Input a number: "))
  y = int(input("Input another number: "))
  print(x/y)
except ValueError:
  print("Please input only numbers")
except ZeroDivisionError:
  print("Cannot divide by zero!")
except:
  print("Unknown error occurred!")

Output:

Input a number: abcd
Please input only numbers
Input a number: 12
Input another number: abcd
Please input only numbers
Input a number: 10
Input another number: 2
5.0
Input a number: 100
Input another number: 0
Cannot divide by zero!

In the example above -

  • The "try" block has code that could raise ValueError or ZeroDivisionError.
  • If the inputs cannot be converted to integers, the first "except" block catches ValueError.
  • The second "except" block catches ZeroDivisionError, which occurs if y is 0
  • Any other exception will be caught by the third generic "except" block without any exception specified.
  • Each "except" block prints a different error message relevant to that exception.
  • The order of "except" blocks matters - Python will check each one in order to find a match.
  • As soon as a matching exception is found, the "except" block is executed, and the rest are skipped.


Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/python-interview/what-is-the-role-of-the-except-block-how-is-it-used-to-catch-exceptions.php