How to Write a 'Try'/'Except' Block That Catches All Exceptions

How can I write a `try`/`except` block that catches all exceptions?

You can but you probably shouldn't:

try:
do_something()
except:
print("Caught it!")

However, this will also catch exceptions like KeyboardInterrupt and you usually don't want that, do you? Unless you re-raise the exception right away - see the following example from the docs:

try:
f = open('myfile.txt')
s = f.readline()
i = int(s.strip())
except IOError as (errno, strerror):
print("I/O error({0}): {1}".format(errno, strerror))
except ValueError:
print("Could not convert data to an integer.")
except:
print("Unexpected error:", sys.exc_info()[0])
raise

Can I catch all exceptions by using try and catch in __main__

As explained here, you can create an exception handler and monkey patch sys.excepthook:

import sys
import logging

logger = logging.getLogger(__name__)

def handle_unhandled_exception(e_type, e_value, e_traceback):
logger.critical("Unhandled exception", exc_info=(e_type, e_value, e_traceback))
do_other_stuff_at_your_convenience()

sys.excepthook = handle_unhandled_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.

Python: How to ignore an exception and proceed?

except Exception:
pass

Python docs for the pass statement

Catch any error in Python

Using except by itself will catch any exception short of a segfault.

try:
something()
except:
fallback()

You might want to handle KeyboardInterrupt separately in case you need to use it to exit your script:

try:
something()
except KeyboardInterrupt:
return
except:
fallback()

There's a nice list of basic exceptions you can catch here. I also quite like the traceback module for retrieving a call stack from the exception. Try traceback.format_exc() or traceback.print_exc() in an exception handler.

How to implement try-catch block in racket?

You're requiring try-catch-match library, but your example comes from try-catch library. These two are different and if you use the correct one, the example code will work:

#lang racket
(require try-catch)

(try [(displayln "body")
(raise 'boom)]
[catch (string? (printf "caught a string\n"))
(symbol? (printf "caught a symbol\n"))])

Return from Try/Catch block in Kotlin

Here's a solution, probably not the best one though:

fun doSomethingMagical(param1: String): UserDefinedObject? {
var result = UserDefinedObject()
//assuming this object has no properties
//if it does you much provide them to initialize it
...
try {
....
if(some expression){
val temp : UserDefinedObject = //some code
result = temp
} catch(e : Exception){
return null
}
return result
}

A better one, depending on whether or not you need the result before the try (I'm assuming you don't), you may be able to do it this way:

fun doSomethingMagical(param1: String): UserDefinedObject? {
return try {
whateverSomeCodeIs() // returns a UserDefinedObject
} catch(e : Exception){
null
}
}

Or this way:

fun doSomethingMagical(param1: String): UserDefinedObject? {
try {
return whateverSomeCodeIs() // returns a UserDefinedObject
} catch(e : Exception){
return null
}
}

Or this way which will imply the return type and doesn't require "return" explicitly:

fun doSomethingMagical(param1: String) = try { whateverSomeCodeIs() } catch(e: Exception) { null }

If you don't want it to be nullable (which is what the "?" indicates) then you would need to return a UserDefinedObject in the catch, allow the exception to be thrown and catch it later, or ensure that an exception can not be thrown.

I'd also recommend that you check out the Kotlin docs. They are pretty informative. Here's a link to their Exceptions section.



Related Topics



Leave a reply



Submit