Catching Unexpected Errors
Catching Unexpected Errors (try-except
)
Unfortunately, it’s impossible to predict all the problems that may occur. However, there’s a construction called try-except that we use when we’re working with unpredictable scenarios. You stick the source code in the try
block, and if there’s a problem with it, the code in the except
block is executed instead.
1try:2 # code that might have an error in it3except:4 # what happens if an error is discovered