Python: One Try Multiple Except

Python: One Try Multiple Except

Yes, it is possible.

try:
...
except FirstException:
handle_first_one()

except SecondException:
handle_second_one()

except (ThirdException, FourthException, FifthException) as e:
handle_either_of_3rd_4th_or_5th()

except Exception:
handle_all_other_exceptions()

See: http://docs.python.org/tutorial/errors.html

The "as" keyword is used to assign the error to a variable so that the error can be investigated more thoroughly later on in the code. Also note that the parentheses for the triple exception case are needed in python 3. This page has more info: Catch multiple exceptions in one line (except block)

Catch multiple exceptions in one line (except block)

From Python Documentation:

An except clause may name multiple exceptions as a parenthesized tuple, for example

except (IDontLikeYouException, YouAreBeingMeanException) as e:
pass

Or, for Python 2 only:

except (IDontLikeYouException, YouAreBeingMeanException), e:
pass

Separating the exception from the variable with a comma will still work in Python 2.6 and 2.7, but is now deprecated and does not work in Python 3; now you should be using as.

Python Try/Except with multiple except blocks

You could add another level of try nesting:

try:
try:
raise KeyError()
except KeyError:
print "Caught KeyError"
raise Exception()
except Exception:
print "Caught Exception"

try/except block catching multiple exceptions

If you want to be able to catch an exception anywhere in a large block of code, the entire thing needs to be within the same try block:

try:
file_name = input("Enter file name: ")
assert ".txt" in file_name, "Error, must be a txt file"
file_fh = open(file_name) # may raise FileNotFoundError
counter = 0
avg = 0
for line in file_fh:
if not line.startswith("X-DSPAM-Confidence:"): continue
avg += float(line[20:-1].strip())
counter = counter + 1
assert counter, "File is empty!"
print("Average spam confidence:", round(avg / counter, 4))
except (AssertionError, FileNotFoundError) as e:
print(e)

In this example, the assert statements will obviously raise an AssertionError with the given message if the condition is not met. The open call will raise FileNotFoundError if the file is missing, so to handle that case all you need to do is make sure your except block includes FileNotFoundError.

Simplify multiple try and except statements

You don't need to put a try/except block after every statement. It would be better to put multiple statements in a try/except block

def my_function(path_a, path_b, tmp_dir)

try:
<shutil.copy to the tmp dir>
war_process = subprocess.run([WAR GENERATION COMMAND], check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
print(war_process.stdout.decode("utf-8"))
except subprocess.CalledProcessError as e:
exit_code = e.returncode
stderror = e.stderr
print(exit_code, stderror)
print(war_process.stderr.decode("utf-8"))

try:
output_folder = os.path.join("/tmp/dir/work", FILE_PATH, ARTIFACT_DATE, FILE_WO_EXTENSION)
file_name = list(glob.glob(os.path.join(output_folder, "*.war")))
file_path = os.path.join(output_folder, file_name)
os.rename(file_path, file_path.split('war')[0] + ".tgz")
file_version = os.path.basename(file_path)
except:
traceback.print_exc()

cmd = "curl -u username -T ....)"

try:
curl_output = subprocess.run([cmd], shell=True, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
print(curl_output.stdout.decode("utf-8"))
except subprocess.CalledProcessError as er:
print(proc_c.stderr.decode("utf-8"))
exit_c = er.returncode
std = er.stderr
print(exit_c, std)
```

How to avoid duplicates when python multiple except executes the same method?

You could catch both exceptions in one except clause, execute todo and then decide to do based on the exception type:

try:
method()
except (ErrorType1, ErrorType2) as e:
todo()
if isinstance(e, ErrorType1):
return
raise

Note - as pointed out by @ShadowRanger in the comments to the question - you should just use raise to re-raise the existing exception, using raise e will raise a second copy of it, resulting in the traceback including the line with raise e on it as well as the line where the original error occurred.

How to handle multiple exceptions in Python 3?

It may be worth checking out the Errors and Exceptions docs.

In short, you can specify behaviour for different Exception types using the except ExceptionType: syntax where ExceptionType is an Exception derived from the Python Exception class - a list of built-in Python exceptions can be found here.

It is important to note that when an Exception is raised in a try block, Python will execute the code within the first Except block that matches the Exception raised in a top-down manner. For this reason, except Exception: is usually found at the bottom in a given try/except chain as to provide default behaviour for unspecified exceptions that may be raised, it is not first as any Exception raised will trigger this behaviour and thus would make other Except statements within the chain moot.

Example

The below example illustrates the above points.

Here eval() has been used for demonstrative purposes only, please be aware of the inherent dangers of using eval() before you consider using it in your own code.

def demo(e):
try:
eval(e)
except ZeroDivisionError as e:
print("ZeroDivisionError caught")
print(e)
except IndexError as e:
print("IndexError caught")
print(e)
except Exception as e:
print("Other Exception caught")
print(e)

examples = ["10/0", "[0,1,2][5]", "int('foo')"]

for e in examples:
demo(e)
print()

Output

ZeroDivisionError caught
division by zero

IndexError caught
list index out of range

Other Exception caught
invalid literal for int() with base 10: 'foo'


Related Topics



Leave a reply



Submit