Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Failing to catch a specific error

Tags:

python

import

I wrote this simple code:

#!/usr/bin/python2.7 -tt

import subprocess

def main()
  try:
    process = subprocess.check_output(['unvalidcommand'],shell=True)
  except CalledProcessError:
    print 'there is the calledProcessError'


if __name__ == '__main__':
  main() 

Expected output: there is the calledProcessError

What I got: NameError: global name 'CalledProcessError' is not defined

like image 611
Bosiwow Avatar asked Jul 31 '14 12:07

Bosiwow


People also ask

What happens if you don't catch an error?

What happens if an exception is not caught? If an exception is not caught (with a catch block), the runtime system will abort the program (i.e. crash) and an exception message will print to the console.

What are the types of error that get handled by catch?

catch can only handle errors that occur in valid code. Such errors are called “runtime errors” or, sometimes, “exceptions”.

Which errors Cannot be handled by catch block?

The only exception that cannot be caught directly is (a framework thrown) StackOverflowException. This makes sense, logically, as you don't have the space in the stack to handle the exception at that point.

How do you handle errors without try catch?

Instead of getting sick of try/catch, there is another way of checking if the executable throws an error, using custom error instances.


2 Answers

def main():
  try:
    process = subprocess.check_output(['unvalidcommand'],shell=True)
  except subprocess.CalledProcessError: # need to use subprocess.CalledProcessError
    print 'there is the calledProcessError'
main()
there is the calledProcessError
/bin/sh: 1: unvalidcommand: not found

Or just import what you need from subprocess:

from subprocess import check_output,CalledProcessError

def main():
  try:
    process = check_output(['unvalidcommand'],shell=True)
  except CalledProcessError:
    print 'there is the calledProcessError'
main()
like image 88
Padraic Cunningham Avatar answered Sep 22 '22 04:09

Padraic Cunningham


subprocess.CalledProcessError is not a builtin exception. You need to qualify the exception name to use it.

except subprocess.CalledProcessError:
       ^^^^^^^^^^^

or you need to import it explicitly:

from subprocess import CalledProcessError
like image 31
falsetru Avatar answered Sep 24 '22 04:09

falsetru