Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making sure that all exceptions are caught in Python

I've been programming in Python for a while now, but my efforts have been mainly creating small utility scripts. I think that Python is a great language because its fun and it makes it easy to write clean code.

However, there is one annoyance I haven't found a cure for: Due to it's dynamic nature, exceptions can be thrown from various sources and they will kill your program if they're not caught. To me, this is a pain for "largish" programs.

In Java (not that I know Java better than I know Python), the compiler actually statically enforces the handling of exceptions so that all possible exceptions are caught. Is it possible to achieve the same with Python?

like image 423
lang2 Avatar asked Jul 25 '11 14:07

lang2


People also ask

How do I see all exceptions in Python?

Try and Except Statement – Catching all Exceptions Try and except statements are used to catch and handle exceptions in Python. Statements that can raise exceptions are kept inside the try clause and the statements that handle the exception are written inside except clause.

How do you catch all exceptions?

Master C and Embedded C Programming- Learn as you go Exception handling is used to handle the exceptions. We can use try catch block to protect the code. Catch block is used to catch all types of exception. The keyword “catch” is used to catch exceptions.

How do you catch multiple exceptions in Python?

By handling multiple exceptions, a program can respond to different exceptions without terminating it. In Python, try-except blocks can be used to catch and respond to one or multiple exceptions. In cases where a process raises more than one possible exception, they can all be handled using a single except clause.

How do you catch errors in Python?

The try block lets you test a block of code for errors. The except block lets you handle the error. The else block lets you execute code when there is no error. The finally block lets you execute code, regardless of the result of the try- and except blocks.


1 Answers

You can catch all exceptions with the simple except: statement. But this is considered dangerous, since this also covers syntactical errors.

The best practice is to cover all possible and expected exception types with one except clause. Consider the following example:

except (IOError, ArgumentError), e:
    print(e)

This example catches the two expected exceptions, all others will fall through and will be written to stderr.

like image 87
Constantinius Avatar answered Oct 18 '22 06:10

Constantinius