Python: How to ignore an exception and proceed?
except Exception:
pass
Python docs for the pass statement
How to properly ignore exceptions
try:
doSomething()
except Exception:
pass
or
try:
doSomething()
except:
pass
The difference is that the second one will also catch KeyboardInterrupt
, SystemExit
and stuff like that, which are derived directly from BaseException
, not Exception
.
See documentation for details:
try
statement- exceptions
However, it is generally bad practice to catch every error - see Why is "except: pass" a bad programming practice?
Ignoring an error message to continue with the loop in python
It is generally a bad practice to suppress errors or exceptions without handling them, but this can be easily done like this:
try:
# block raising an exception
except:
pass # doing nothing on exception
This can obviously be used in any other control statement, such as a loop:
for i in xrange(0,960):
try:
... run your code
except:
pass
How to ignore exceptions and proceed with whole blocks (multiple lines) in python?
This can be achieved with the fuckit
python module.
Here is the code modified from your example:
#!/usr/bin/env python3
import fuckit
def one():
raise Exception
print( 'one' )
def two():
print( 'two' )
@fuckit
def helper():
one()
two()
helper()
And an example execution:
user@disp3221:~$ sudo python3 -m pip install fuckit
Collecting fuckit
Downloading https://files.pythonhosted.org/packages/cc/f4/0952081f9e52866f4a520e2d92d27ddf34f278d37204104e4be869c6911d/fuckit-4.8.1.zip
Building wheels for collected packages: fuckit
Running setup.py bdist_wheel for fuckit ... done
Stored in directory: /root/.cache/pip/wheels/a9/24/e6/a3e32536d1b2975c23ac9f6f1bdbc591d7b968e5e0ce6b4a4f
Successfully built fuckit
Installing collected packages: fuckit
Successfully installed fuckit-4.8.1
user@disp3221:~$
user@disp3221:~$ ./test.py
two
user@disp3221:~$
python ignore whichever line that causes error and continue running the code after that line
What you want to do (try with restart) is not possible in Python. Lisp can do it (http://www.gigamonkeys.com/book/beyond-exception-handling-conditions-and-restarts.html), and you can implement it in Scheme using call/cc
.
Python ignore and skip error line, and continue with the next line
This means that you are successfully catching an error and going to the condition in except
statement and as a result your data is never loaded and the variable data
is never defined. And then when you try to save data to csv, this triggers an error.
What you should do instead is to put your to_csv
statement inside try-except
as well:
import simplejson
import pandas as pd
with open('/tmp/test.json') as f:
try:
data = pd.DataFrame(simplejson.loads(line) for line in f)
data.to_csv('/tmp/data.csv')
except Exception as e:
pass
Also, it is a horrible anti-pattern in Python to do except Exception as e: pass
. This will result in the code that is nigh impossible to debug because you are catching every single error that might happen and not specifically the error you expect to happen. When you do this you should either log the full error stack or print it to console to be aware of what exact error you are catching:
try:
data = pd.DataFrame(simplejson.loads(line) for line in f)
except Exception as e:
err = str(e)
print(err)
Or you should be catching a specific error that you expect to happen here:
try:
data = pd.DataFrame(simplejson.loads(line) for line in f)
except FileNotFoundError:
pass
Ignore exception in Python
pass
is the keyword you are looking for.
Python ignore all errors and continue running
You can catch errors and ignore them (if it makes sense). eg if the call foo.bar()
could cause an error use
try:
foo.bar()
except: #catch everything, should generally be avoided.
#what should happen when an error occurs
If you only want to ignore a certain type of error use (recommended) (python 2)
try:
foo.bar()
except <ERROR TO IGNORE>, e:
#what should happen when an error occurs
or (python 3)
try:
foo.bar()
except <ERROR TO IGNORE> as e:
#what should happen when an error occurs
See the Python documentation on handling exceptions for more information.
Related Topics
How to Enumerate a Range of Numbers Starting at 1
How to Check If an Object Is a List or Tuple (But Not String)
How to Add a Custom Loglevel to Python's Logging Facility
How to Initialize the Base (Super) Class
How to Find the First Key in a Dictionary
Convert a List of Tuples to a List of Lists
Search by Objectid in Mongodb with Pymongo
Return SQL Table as JSON in Python
Removing List of Words from a String
How to Correctly Parse Utf-8 Encoded HTML to Unicode Strings with Beautifulsoup
Real World Example About How to Use Property Feature in Python
Could Not Find a Version That Satisfies the Requirement <Package>
Does Python Have Class Prototypes (Or Forward Declarations)
Format String Unused Named Arguments
How to Make Sessions Timeout in Flask
Overriding Properties in Python