Catching Specific Exceptions Vs. Raising Exceptions

Post Reply
charan
Posts: 48
Joined: Fri Nov 23, 2018 5:31 am

Catching Specific Exceptions Vs. Raising Exceptions

Post by charan » Fri Nov 30, 2018 8:37 am

What is Catching Specific Exceptions in Python and Raising Exceptions with an examples?

swathi
Posts: 134
Joined: Fri Nov 23, 2018 2:52 am

Re: Catching Specific Exceptions Vs. Raising Exceptions

Post by swathi » Fri Nov 30, 2018 8:43 am

Catching Specific Exceptions :

This is not a good programming practice as it will catch all exceptions and handle every case in the same way. We can specify which exceptions an except clause will catch.

A try clause can have any number of except clause to handle them differently but only one will be executed in case an exception occurs.
We can use a tuple of values to specify multiple exceptions in an except clause. Here is an example pseudo code.

try:
# do something
pass

except ValueError:
# handle ValueError exception
pass

except (TypeError, ZeroDivisionError):
# handle multiple exceptions
# TypeError and ZeroDivisionError
pass

except:
# handle all other exceptions
pass

Raising Exceptions :

In Python programming, exceptions are raised when corresponding errors occur at run time, but we can forcefully raise it using the keyword raise.
We can also optionally pass in value to the exception to clarify why that exception was raised.

Example :

>>> raise KeyboardInterrupt
Traceback (most recent call last):
...
KeyboardInterrupt

>>> raise MemoryError("This is an argument")
Traceback (most recent call last):
...
MemoryError: This is an argument

>>> try:
... a = int(input("Enter a positive integer: "))
... if a <= 0:
... raise ValueError("That is not a positive number!")
... except ValueError as ve:
... print(ve)
...
Enter a positive integer: -2
That is not a positive number!

Post Reply

Return to “Exception Handling in Python”