python exception handling - how to do it pythonic?

  • Last Update :
  • Techknowledgy :

After the except clause(s), you can include an else-clause. The code in the else-block executes if the code in the try: block does not raise an exception.,If you have some suspicious code that may raise an exception, you can defend your program by placing the suspicious code in a try: block. After the try: block, include an except: statement, followed by a block of code which handles the problem as elegantly as possible.,This kind of a try-except statement catches all the exceptions that occur. Using this kind of try-except statement is not considered a good programming practice though, because it catches all exceptions but does not make the programmer identify the root cause of the problem that may occur.,Note: In order to catch an exception, an "except" clause must refer to the same exception thrown either class object or simple string. For example, to capture above exception, we must write the except clause as follows −

The syntax for assert is −

assert Expression[, Arguments]
2._
#!/usr/bin/python

def KelvinToFahrenheit(Temperature):
   assert(Temperature >= 0), "Colder than absolute zero!"
return ((Temperature - 273) * 1.8) + 32
print KelvinToFahrenheit(273)
print int(KelvinToFahrenheit(505.78))
print KelvinToFahrenheit(-5)

When the above code is executed, it produces the following result −

32.0
451
Traceback (most recent call last):
File "test.py", line 9, in <module>
   print KelvinToFahrenheit(-5)
   File "test.py", line 4, in KelvinToFahrenheit
   assert (Temperature >= 0),"Colder than absolute zero!"
   AssertionError: Colder than absolute zero!
5._
#!/usr/bin/python

try:
fh = open("testfile", "w")
fh.write("This is my test file for exception handling!!")
except IOError:
   print "Error: can\'t find file or read data"
else:
   print "Written content in the file successfully"
fh.close()

This produces the following result −

Written content in the file successfully

Suggestion : 2

Last Updated : 15 Jul, 2022

Second element = 2
An error occurred

Second element = 2
An error occurred

A try statement can have more than one except clause, to specify handlers for different exceptions. Please note that at most one handler will be executed. For example, we can add IndexError in the above code. The general syntax for adding specific exceptions are – 

try:
# statement(s)
except IndexError:
   # statement(s)
except ValueError:
   # statement(s)

If you comment on the line fun(3), the output will be 

NameError Occurred and Handled

Syntax:

try:
# Some Code....

except:
   # optional block
# Handling of exception(
   if required)

else:
   # execute
if no exception

finally:
# Some code.....(always executed)

The output of the above code will simply line printed as “An exception” but a Runtime error will also occur in the last due to the raise statement in the last line. So, the output on your command line will look like 

Traceback (most recent call last):
File "/home/d6ec14ca595b97bff8d8034bbf212a9f.py", line 5, in <module>
   raise NameError("Hi there") # Raise Error
   NameError: Hi there

ZeroDivisionError Occurred and Handled

Suggestion : 3

The critical operation which can raise an exception is placed inside the try clause. The code that handles the exceptions is written in the except clause.,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 should catch.,In Python, exceptions can be handled using a try statement.,In this program, we loop through the values of the randomList list. As previously mentioned, the portion that can cause an exception is placed inside the try block.

We can thus choose what operations to perform once we have caught the exception. Here is a simple example.

#
import module sys to get the type of exception
import sys

randomList = ['a', 0, 2]

for entry in randomList:
   try:
   print("The entry is", entry)
r = 1 / int(entry)
break
except:
   print("Oops!", sys.exc_info()[0], "occurred.")
print("Next entry.")
print()
print("The reciprocal of", entry, "is", r)

Output

The entry is a
Oops! <class 'ValueError'> occurred.
   Next entry.

   The entry is 0
   Oops! <class 'ZeroDivisionError'> occured.
      Next entry.

      The entry is 2
      The reciprocal of 2 is 0.5

Since every exception in Python inherits from the base Exception class, we can also perform the above task in the following way:

#
import module sys to get the type of exception
import sys

randomList = ['a', 0, 2]

for entry in randomList:
   try:
   print("The entry is", entry)
r = 1 / int(entry)
break
except Exception as e:
   print("Oops!", e.__class__, "occurred.")
print("Next entry.")
print()
print("The reciprocal of", entry, "is", r)

We can optionally pass values to the exception to clarify why that exception was raised.

>>> 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!

Let's look at an example:

# program to print the reciprocal of even numbers

try:
num = int(input("Enter a number: "))
assert num % 2 == 0
except:
   print("Not an even number!")
else:
   reciprocal = 1 / num
print(reciprocal)

Suggestion : 4

In Python, we catch exceptions and handle them using try and except code blocks. The try clause contains the code that can raise an exception, while the except clause contains the code lines that handle the exception. Let's see if we can access the index from the array, which is more than the array's length, and handle the resulting exception.,We raise a user-defined exception in the try block and then handle the exception in the except block. An example of the class EmptyError is created using the variable var.,The try clause's exception(s) are detected and handled using the except function.,We learned about different methods to raise, catch, and handle Python exceptions after learning the distinction between syntax errors and exceptions. We learned about these clauses in this tutorial:

    if (s != o:
       ^
       SyntaxError: invalid syntax
      2 string = "Python Exceptions"
      4
      for s in string:
         -- -- > 5
      if (s != o):
         6 print(s)

      NameError: name 'o'
      is not defined
The index and element from the array is 0 Python
The index and element from the array is 1 Exceptions
The index and element from the array is 2
try and except
Index out of range
      1 num = [3, 4, 5, 7]
      2
      if len(num) > 3:
         -- -- > 3 raise Exception(f "Length of the given list must be less than or equal to 3 but is {len(num)}")

      Exception: Length of the given list must be less than or equal to 3 but is 4
      7 #Calling
      function and passing the values
      -- -- > 8 print(square_root(36))
      9 print(square_root(-36))

      Input In[23], in square_root(Number)
      3 def square_root(Number):
         -- -- > 4 assert(Number < 0), "Give a positive integer"
      5
      return Number ** (1 / 2)

      AssertionError: Give a positive integer
0.25
We cannot divide by zero

Suggestion : 5

Python uses try and except keywords to handle exceptions. Both keywords are followed by indented blocks. , 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. , Here, the raised exception is a ValueError type. However, you can define your custom exception type to be raised. Visit Python docs to know more about user defined exceptions. , 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.

try:
#statements in
   try block
except:
   #executed when error in
   try block
try:
a = 5
b = '0'
print(a / b)
except:
   print('Some error occurred.')
print("Out of try except blocks.")
Some error occurred.
Out of
   try except blocks.
try:
a = 5
b = '0'
print(a + b)
except TypeError:
   print('Unsupported operation')
print("Out of try except blocks")
Unsupported operation
Out of
   try except blocks
try:
a = 5
b = 0
print(a / b)
except TypeError:
   print('Unsupported operation')
except ZeroDivisionError:
   print('Division by zero not allowed')
print('Out of try except blocks')

Suggestion : 6

8.3. Handling Exceptions,8.4. Raising Exceptions,8. Errors and Exceptions,8.5. Exception Chaining

>>> while True print('Hello world')
File "<stdin>", line 1
   while True print('Hello world')
   ^
   SyntaxError: invalid syntax
>>> 10 * (1/0)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
      ZeroDivisionError: division by zero
      >>> 4 + spam*3
      Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
            NameError: name 'spam' is not defined
            >>> '2' + 2
            Traceback (most recent call last):
            File "<stdin>", line 1, in <module>
                  TypeError: can only concatenate str (not "int") to str
>>>
while True:
   ...
   try:
   ...x = int(input("Please enter a number: "))
   ...
   break
   ...except ValueError:
   ...print("Oops!  That was no valid number.  Try again...")
   ...
...except(RuntimeError, TypeError, NameError):
   ...pass
class B(Exception):
   pass

class C(B):
   pass

class D(C):
   pass

for cls in [B, C, D]:
   try:
   raise cls()
except D:
   print("D")
except C:
   print("C")
except B:
   print("B")
import sys

try:
f = open('myfile.txt')
s = f.readline()
i = int(s.strip())
except OSError as err:
   print("OS error: {0}".format(err))
except ValueError:
   print("Could not convert data to an integer.")
except BaseException as err:
   print(f "Unexpected {err=}, {type(err)=}")
raise

Suggestion : 7

Python ceases the action whenever it encounters any exception. It only completes the execution after the exceptions are handled.  Here is an example of exception handling.,Manual exceptions increase the affectivity in the execution of the program. The manual exceptions save Python from encountering any exceptions itself. Hence, smoothing the execution of the program.,Exception classes only function as any regular class. However some simplicity is kept in classes to provide a few attributes improving the efficiency of the exception handling in Python. These attributes can then further be used for extraction by handlers in case of the exceptions.,The usage of multiple exceptions is a very handy process for the programmers. Since, the real world execution requires some aspects which can be in deviation with analytical aspect, the exceptions are handy to use.

Syntax for try except else:

Try:
   Print A.
Except exception
If A is exception, then execute this block.
Else
If there is no exception, then execute this block.

Error:

>>>
while True print('Hello world')
File "", line 1
while True print('Hello world') ^
   SyntaxError: invalid syntax

Example of a 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

Here is another example:

try:
num1 = 7
num2 = 0
print(num1 / num2)
print(“Done calculation”)
except ZeroDivisonError:
   print(“Infinity”)

Output:

Infinity