Posts

Showing posts with the label Exception Handling

Catch Multiple Exceptions In One Line (except Block)

Answer : 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 . How do I catch multiple exceptions in one line (except block) Do this: try: may_raise_specific_errors(): except (SpecificErrorOne, SpecificErrorTwo) as error: handle(error) # might log or have some other default behavior... The parentheses are required due to older syntax that used the commas to assign the error object to a name. The as keyword is used for the assignment. You can use any name for the error object, I prefer error personally. Best Practice To do this in a manner currently and ...

Catching An Exception While Using A Python 'with' Statement

Answer : from __future__ import with_statement try: with open( "a.txt" ) as f : print f.readlines() except EnvironmentError: # parent of IOError, OSError *and* WindowsError where available print 'oops' If you want different handling for errors from the open call vs the working code you could do: try: f = open('foo.txt') except IOError: print('error') else: with f: print f.readlines() The best "Pythonic" way to do this, exploiting the with statement, is listed as Example #6 in PEP 343, which gives the background of the statement. @contextmanager def opened_w_error(filename, mode="r"): try: f = open(filename, mode) except IOError, err: yield None, err else: try: yield f, None finally: f.close() Used as follows: with opened_w_error("/etc/passwd", "a") as (f, err): if err: print "IO...

Await Task.WhenAll(tasks) Exception Handling, Log All Exceptions From The Tasks

Answer : You've fallen foul of lazy evaluation - the result of Select will create a new set of tasks each time you iterate over it. You can fix this just by calling ToList() : var tasks = _factory.CreateMessage(settings) .Select(msg => SendScans(msg)) .ToList(); That way the set of tasks that you're awaiting will be the same set of tasks checked with your foreach loop. Instead of iterating over all tasks, you can get the Exceptions (if any) from the Task.WhenAll -Task: var taskResult = Task.WhenAll(tasks); try { await taskResult; } catch (Exception e) { if (taskResult.IsCanceled) { // Cancellation is most likely due to a shared cancellation token. Handle as needed, possibly check if ((TaskCanceledException)e).CancellationToken == token etc. } else if (taskResult.IsFaulted) { // use taskResult.Exception which is an AggregateException - which you can iterate over (it's a tree...