Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to catch all exceptions in Try/Catch Block Python?

I am writing python code to install all the library packages required by my program in the linux environment.So the linux may contain python 2.7 or 2.6 or both so I have developed a try and except block codes that will install pip packages in linux. Try block code consists of python 2.7 version pip install and Catch block contains python 2.6 version pip install. My Problem is the peace of code is working fine, when i tried to install pandas in python 2.6 its getting me some errror. I want to catch that exception. Can you please tell me how to improve my try except blocks to catch that exception

required_libraries = ['pytz','requests','pandas']
try:
   from subprocess import check_output
   pip27_path = subprocess.check_output(['sudo','find','/','-name','pip2.7'])
   lib_installs = [subprocess.call((['sudo',pip27_path.replace('\n',''),'install', i])) for i in required_libraries]
except:
   p = subprocess.Popen(['sudo','find','/','-name','pip2.6'], stdout=subprocess.PIPE);pip26_path, err = p.communicate()
   lib_installs = [subprocess.call((['sudo',pip26_path.replace('\n',''),'install', i])) for i in required_libraries]
like image 646
Rahul Avatar asked Dec 08 '17 17:12

Rahul


People also ask

Does try catch catch all exceptions?

We can use try catch block to protect the code. Catch block is used to catch all types of exception. The keyword “catch” is used to catch exceptions.

Which exception catch all exceptions in Python?

Try and Except Statement – Catching all Exceptions Try and except statements are used to catch and handle exceptions in Python. Statements that can raise exceptions are kept inside the try clause and the statements that handle the exception are written inside except clause.

How do you catch and print exceptions in Python?

The first method to catch and print the exception messages in python is by using except and try statement. If the user enters anything except the integer, we want the program to skip that input and move to the next value. In this way, our program will not crash and will catch and print the exception message.


1 Answers

You can catch several exceptions using one block. Let's use Exception and ArithmeticError for exceptions.

try:
    # Do something
    print(q)

# Catch exceptions  
except (Exception, ArithmeticError) as e:
    template = "An exception of type {0} occurred. Arguments:\n{1!r}"
    message = template.format(type(e).__name__, e.args)
    print (message)

If you need to catch several exceptions and handle each one on its own then you'd write an except statement for each one.

try:
    # Do something
    print(q)

# Catch exceptions  
except Exception as e:
    print (1)

except ArithmeticError as e:
    print (2)

# Code to be executed if the try clause succeeded with no errors or no return/continue/break statement

else:
    print (3)

You can also check if the exception is of type "MyCustomException" for example using if statements.

if isinstance(e, MyCustomException):
    # Do something
    print(1)

As for your problem, I suggest splitting the code into two functions.

install(required_libraries)

def install(required_libraries, version='pip2.7'):
    # Perform installation
    try:
        from subprocess import check_output
        pip27_path = subprocess.check_output(['sudo','find','/','-name', version])
        lib_installs = [subprocess.call((['sudo',pip27_path.replace('\n',''),'install', i])) for i in required_libraries]

    except Exception as e:
        backup(required_libraries)

def backup(required_libraries, version='pip2.6'):
    try:
        p = subprocess.Popen(['sudo','find','/','-name',version]], stdout=subprocess.PIPE);pip26_path, err = p.communicate()
        lib_installs = [subprocess.call((['sudo',pip26_path.replace('\n',''),'install', i])) for i in required_libraries]

    except Exception as e:
        template = "An exception of type {0} occurred. Arguments:\n{1!r}"
        message = template.format(type(e).__name__, e.args)
        print (message)

        #Handle exception

Note: I didn't test this, I'm no expert as well so I hope I can help.

Useful links:

  1. Built-in Exceptions
  2. Errors and Exceptions
  3. Compound statements
like image 73
mrhallak Avatar answered Sep 28 '22 08:09

mrhallak