Python/Django: how do I determine the class to specify in an “except” statement?

Multi tool use
I am working with some Python/Django code that I inherited. In it there is a DB call surrounded by a try block, with an "except Exception ex" statement to catch all exceptions. I want to be more selective, and catch only the exception type that I anticipate. By examining the Exception object that is caught, I can tell that it's of type "DatabaseError".
The comments in my code below show the many things I have tried, based on Googling the question and searching here, along with the errors that Python gives me when I try them. Most frustrating is that I've found plenty of examples on the web of code the people say works, that looks just like what I'm trying. But the code samples I find generally don't include the "import" lines.
I suspect I need to import something more, but I can't figure out what.
import cx_Oracle
## import cx_Oracle.DatabaseError # creates an error saying "No name 'DatabaseError in module 'cx_Oracle'"
## from cx_Oracle import DatabaseError # creates an error saying "No name 'DatabaseError in module 'cx_Oracle'"
. . .
connection = connections['ims_db']
sqlUpdateQuery = "SELECT * FROM LOCKING WHERE IDENT={0} AND KEY_ID='SL_KEY' FOR UPDATE NOWAIT".format(self.serviceUid)
cursor = connection.cursor()
try:
cursor.execute(sqlUpdateQuery)
# this gets the error "Undefined variable 'Database'"
## except Database.DatabaseError as dbe3:
# this gets the error "Undefined variable 'Oracle'"
## except Oracle.DatabaseError as dbe2:
# this gets the error "Module 'cx_Oracle' has no 'DatabaseError' member"
## except cx_Oracle.DatabaseError as dbe:
# this gets the error "Undefined variable 'DatabaseError'"
## except DatabaseError as dbe:
# this gets the error "Catching an exception which doesn't inherit from BaseException: cx_Oracle"
## except cx_Oracle as dbe:
# this gets the error "Module cx_Oracle has no '_error' member"
## except cx_Oracle._Error as dbe:
except Exception as ex:
# This gets the error "Module cx_Oracle has no 'DatabaseError' member"
## if isinstance(ex, cx_Oracle.DatabaseError) :
# This gets the error "Undefined variable 'DatabaseError'"
## if isinstance(ex, DatabaseError) :
className = type(ex).__name__
# This logs "... class = DatabaseError ..."
log.error("Exception (class = {1}) while locking service {0}".format(self.serviceUid, className))
args = ex.args
arg0=args[0]
# arg0ClassName is "_Error"
arg0ClassName = type(arg0).__name__
code = arg0.code
# codeClassName is "int"
codeClassName = type(code).__name__
msg = "Exception, code = {0}".format(code)
log.debug(msg)
raise
python exception exception-handling cx-oracle
add a comment |
I am working with some Python/Django code that I inherited. In it there is a DB call surrounded by a try block, with an "except Exception ex" statement to catch all exceptions. I want to be more selective, and catch only the exception type that I anticipate. By examining the Exception object that is caught, I can tell that it's of type "DatabaseError".
The comments in my code below show the many things I have tried, based on Googling the question and searching here, along with the errors that Python gives me when I try them. Most frustrating is that I've found plenty of examples on the web of code the people say works, that looks just like what I'm trying. But the code samples I find generally don't include the "import" lines.
I suspect I need to import something more, but I can't figure out what.
import cx_Oracle
## import cx_Oracle.DatabaseError # creates an error saying "No name 'DatabaseError in module 'cx_Oracle'"
## from cx_Oracle import DatabaseError # creates an error saying "No name 'DatabaseError in module 'cx_Oracle'"
. . .
connection = connections['ims_db']
sqlUpdateQuery = "SELECT * FROM LOCKING WHERE IDENT={0} AND KEY_ID='SL_KEY' FOR UPDATE NOWAIT".format(self.serviceUid)
cursor = connection.cursor()
try:
cursor.execute(sqlUpdateQuery)
# this gets the error "Undefined variable 'Database'"
## except Database.DatabaseError as dbe3:
# this gets the error "Undefined variable 'Oracle'"
## except Oracle.DatabaseError as dbe2:
# this gets the error "Module 'cx_Oracle' has no 'DatabaseError' member"
## except cx_Oracle.DatabaseError as dbe:
# this gets the error "Undefined variable 'DatabaseError'"
## except DatabaseError as dbe:
# this gets the error "Catching an exception which doesn't inherit from BaseException: cx_Oracle"
## except cx_Oracle as dbe:
# this gets the error "Module cx_Oracle has no '_error' member"
## except cx_Oracle._Error as dbe:
except Exception as ex:
# This gets the error "Module cx_Oracle has no 'DatabaseError' member"
## if isinstance(ex, cx_Oracle.DatabaseError) :
# This gets the error "Undefined variable 'DatabaseError'"
## if isinstance(ex, DatabaseError) :
className = type(ex).__name__
# This logs "... class = DatabaseError ..."
log.error("Exception (class = {1}) while locking service {0}".format(self.serviceUid, className))
args = ex.args
arg0=args[0]
# arg0ClassName is "_Error"
arg0ClassName = type(arg0).__name__
code = arg0.code
# codeClassName is "int"
codeClassName = type(code).__name__
msg = "Exception, code = {0}".format(code)
log.debug(msg)
raise
python exception exception-handling cx-oracle
cx-oracle.readthedocs.io/en/latest/module.html listscx_Oracle.DatabaseError
. Maybe a different "version"? A shadowing module?
– user2864740
Nov 16 '18 at 0:48
Thank you for the suggestions. I had previously looked at either this or similar documentation. I would be very astonished if we had a different version of cx_Oracle kicking around, but who knows. I'll have to check tomorrow, when I have access. But the very fact that className is "DatabaseError" indicates that I'm using a version that matches this documentation.
– Topher
Nov 16 '18 at 3:04
add a comment |
I am working with some Python/Django code that I inherited. In it there is a DB call surrounded by a try block, with an "except Exception ex" statement to catch all exceptions. I want to be more selective, and catch only the exception type that I anticipate. By examining the Exception object that is caught, I can tell that it's of type "DatabaseError".
The comments in my code below show the many things I have tried, based on Googling the question and searching here, along with the errors that Python gives me when I try them. Most frustrating is that I've found plenty of examples on the web of code the people say works, that looks just like what I'm trying. But the code samples I find generally don't include the "import" lines.
I suspect I need to import something more, but I can't figure out what.
import cx_Oracle
## import cx_Oracle.DatabaseError # creates an error saying "No name 'DatabaseError in module 'cx_Oracle'"
## from cx_Oracle import DatabaseError # creates an error saying "No name 'DatabaseError in module 'cx_Oracle'"
. . .
connection = connections['ims_db']
sqlUpdateQuery = "SELECT * FROM LOCKING WHERE IDENT={0} AND KEY_ID='SL_KEY' FOR UPDATE NOWAIT".format(self.serviceUid)
cursor = connection.cursor()
try:
cursor.execute(sqlUpdateQuery)
# this gets the error "Undefined variable 'Database'"
## except Database.DatabaseError as dbe3:
# this gets the error "Undefined variable 'Oracle'"
## except Oracle.DatabaseError as dbe2:
# this gets the error "Module 'cx_Oracle' has no 'DatabaseError' member"
## except cx_Oracle.DatabaseError as dbe:
# this gets the error "Undefined variable 'DatabaseError'"
## except DatabaseError as dbe:
# this gets the error "Catching an exception which doesn't inherit from BaseException: cx_Oracle"
## except cx_Oracle as dbe:
# this gets the error "Module cx_Oracle has no '_error' member"
## except cx_Oracle._Error as dbe:
except Exception as ex:
# This gets the error "Module cx_Oracle has no 'DatabaseError' member"
## if isinstance(ex, cx_Oracle.DatabaseError) :
# This gets the error "Undefined variable 'DatabaseError'"
## if isinstance(ex, DatabaseError) :
className = type(ex).__name__
# This logs "... class = DatabaseError ..."
log.error("Exception (class = {1}) while locking service {0}".format(self.serviceUid, className))
args = ex.args
arg0=args[0]
# arg0ClassName is "_Error"
arg0ClassName = type(arg0).__name__
code = arg0.code
# codeClassName is "int"
codeClassName = type(code).__name__
msg = "Exception, code = {0}".format(code)
log.debug(msg)
raise
python exception exception-handling cx-oracle
I am working with some Python/Django code that I inherited. In it there is a DB call surrounded by a try block, with an "except Exception ex" statement to catch all exceptions. I want to be more selective, and catch only the exception type that I anticipate. By examining the Exception object that is caught, I can tell that it's of type "DatabaseError".
The comments in my code below show the many things I have tried, based on Googling the question and searching here, along with the errors that Python gives me when I try them. Most frustrating is that I've found plenty of examples on the web of code the people say works, that looks just like what I'm trying. But the code samples I find generally don't include the "import" lines.
I suspect I need to import something more, but I can't figure out what.
import cx_Oracle
## import cx_Oracle.DatabaseError # creates an error saying "No name 'DatabaseError in module 'cx_Oracle'"
## from cx_Oracle import DatabaseError # creates an error saying "No name 'DatabaseError in module 'cx_Oracle'"
. . .
connection = connections['ims_db']
sqlUpdateQuery = "SELECT * FROM LOCKING WHERE IDENT={0} AND KEY_ID='SL_KEY' FOR UPDATE NOWAIT".format(self.serviceUid)
cursor = connection.cursor()
try:
cursor.execute(sqlUpdateQuery)
# this gets the error "Undefined variable 'Database'"
## except Database.DatabaseError as dbe3:
# this gets the error "Undefined variable 'Oracle'"
## except Oracle.DatabaseError as dbe2:
# this gets the error "Module 'cx_Oracle' has no 'DatabaseError' member"
## except cx_Oracle.DatabaseError as dbe:
# this gets the error "Undefined variable 'DatabaseError'"
## except DatabaseError as dbe:
# this gets the error "Catching an exception which doesn't inherit from BaseException: cx_Oracle"
## except cx_Oracle as dbe:
# this gets the error "Module cx_Oracle has no '_error' member"
## except cx_Oracle._Error as dbe:
except Exception as ex:
# This gets the error "Module cx_Oracle has no 'DatabaseError' member"
## if isinstance(ex, cx_Oracle.DatabaseError) :
# This gets the error "Undefined variable 'DatabaseError'"
## if isinstance(ex, DatabaseError) :
className = type(ex).__name__
# This logs "... class = DatabaseError ..."
log.error("Exception (class = {1}) while locking service {0}".format(self.serviceUid, className))
args = ex.args
arg0=args[0]
# arg0ClassName is "_Error"
arg0ClassName = type(arg0).__name__
code = arg0.code
# codeClassName is "int"
codeClassName = type(code).__name__
msg = "Exception, code = {0}".format(code)
log.debug(msg)
raise
python exception exception-handling cx-oracle
python exception exception-handling cx-oracle
edited Nov 16 '18 at 2:58
Topher
asked Nov 16 '18 at 0:41
TopherTopher
345
345
cx-oracle.readthedocs.io/en/latest/module.html listscx_Oracle.DatabaseError
. Maybe a different "version"? A shadowing module?
– user2864740
Nov 16 '18 at 0:48
Thank you for the suggestions. I had previously looked at either this or similar documentation. I would be very astonished if we had a different version of cx_Oracle kicking around, but who knows. I'll have to check tomorrow, when I have access. But the very fact that className is "DatabaseError" indicates that I'm using a version that matches this documentation.
– Topher
Nov 16 '18 at 3:04
add a comment |
cx-oracle.readthedocs.io/en/latest/module.html listscx_Oracle.DatabaseError
. Maybe a different "version"? A shadowing module?
– user2864740
Nov 16 '18 at 0:48
Thank you for the suggestions. I had previously looked at either this or similar documentation. I would be very astonished if we had a different version of cx_Oracle kicking around, but who knows. I'll have to check tomorrow, when I have access. But the very fact that className is "DatabaseError" indicates that I'm using a version that matches this documentation.
– Topher
Nov 16 '18 at 3:04
cx-oracle.readthedocs.io/en/latest/module.html lists
cx_Oracle.DatabaseError
. Maybe a different "version"? A shadowing module?– user2864740
Nov 16 '18 at 0:48
cx-oracle.readthedocs.io/en/latest/module.html lists
cx_Oracle.DatabaseError
. Maybe a different "version"? A shadowing module?– user2864740
Nov 16 '18 at 0:48
Thank you for the suggestions. I had previously looked at either this or similar documentation. I would be very astonished if we had a different version of cx_Oracle kicking around, but who knows. I'll have to check tomorrow, when I have access. But the very fact that className is "DatabaseError" indicates that I'm using a version that matches this documentation.
– Topher
Nov 16 '18 at 3:04
Thank you for the suggestions. I had previously looked at either this or similar documentation. I would be very astonished if we had a different version of cx_Oracle kicking around, but who knows. I'll have to check tomorrow, when I have access. But the very fact that className is "DatabaseError" indicates that I'm using a version that matches this documentation.
– Topher
Nov 16 '18 at 3:04
add a comment |
1 Answer
1
active
oldest
votes
The correct syntax is as follows:
try:
cur.execute("some_sql_statement")
except cx_Oracle.DatabaseError as e:
error, = e.args
print("CONTEXT:", error.context)
print("MESSAGE:", error.message)
You can see that syntax in a few of the samples (like TypeHandlers.py) that you can find here: https://github.com/oracle/python-cx_Oracle/tree/master/samples.
Try running the samples and working with them to see if you can resolve your issue. If not, please create an issue containing a complete runnable sample here: https://github.com/oracle/python-cx_Oracle/issues.
I suspect I may be missing something in my import statements. What I have is: "import cx_Oracle" Should I have something more, or different?
– Topher
Nov 20 '18 at 20:26
All you need is import cx_Oracle. Take a look at the samples and you'll see what I mean.
– Anthony Tuininga
Nov 21 '18 at 20:37
I've learned from an unrelated posting that these "errors" are a bug in PyLint. I haven't had time to verify this yet.
– Topher
Nov 22 '18 at 22:37
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53329830%2fpython-django-how-do-i-determine-the-class-to-specify-in-an-except-statement%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
The correct syntax is as follows:
try:
cur.execute("some_sql_statement")
except cx_Oracle.DatabaseError as e:
error, = e.args
print("CONTEXT:", error.context)
print("MESSAGE:", error.message)
You can see that syntax in a few of the samples (like TypeHandlers.py) that you can find here: https://github.com/oracle/python-cx_Oracle/tree/master/samples.
Try running the samples and working with them to see if you can resolve your issue. If not, please create an issue containing a complete runnable sample here: https://github.com/oracle/python-cx_Oracle/issues.
I suspect I may be missing something in my import statements. What I have is: "import cx_Oracle" Should I have something more, or different?
– Topher
Nov 20 '18 at 20:26
All you need is import cx_Oracle. Take a look at the samples and you'll see what I mean.
– Anthony Tuininga
Nov 21 '18 at 20:37
I've learned from an unrelated posting that these "errors" are a bug in PyLint. I haven't had time to verify this yet.
– Topher
Nov 22 '18 at 22:37
add a comment |
The correct syntax is as follows:
try:
cur.execute("some_sql_statement")
except cx_Oracle.DatabaseError as e:
error, = e.args
print("CONTEXT:", error.context)
print("MESSAGE:", error.message)
You can see that syntax in a few of the samples (like TypeHandlers.py) that you can find here: https://github.com/oracle/python-cx_Oracle/tree/master/samples.
Try running the samples and working with them to see if you can resolve your issue. If not, please create an issue containing a complete runnable sample here: https://github.com/oracle/python-cx_Oracle/issues.
I suspect I may be missing something in my import statements. What I have is: "import cx_Oracle" Should I have something more, or different?
– Topher
Nov 20 '18 at 20:26
All you need is import cx_Oracle. Take a look at the samples and you'll see what I mean.
– Anthony Tuininga
Nov 21 '18 at 20:37
I've learned from an unrelated posting that these "errors" are a bug in PyLint. I haven't had time to verify this yet.
– Topher
Nov 22 '18 at 22:37
add a comment |
The correct syntax is as follows:
try:
cur.execute("some_sql_statement")
except cx_Oracle.DatabaseError as e:
error, = e.args
print("CONTEXT:", error.context)
print("MESSAGE:", error.message)
You can see that syntax in a few of the samples (like TypeHandlers.py) that you can find here: https://github.com/oracle/python-cx_Oracle/tree/master/samples.
Try running the samples and working with them to see if you can resolve your issue. If not, please create an issue containing a complete runnable sample here: https://github.com/oracle/python-cx_Oracle/issues.
The correct syntax is as follows:
try:
cur.execute("some_sql_statement")
except cx_Oracle.DatabaseError as e:
error, = e.args
print("CONTEXT:", error.context)
print("MESSAGE:", error.message)
You can see that syntax in a few of the samples (like TypeHandlers.py) that you can find here: https://github.com/oracle/python-cx_Oracle/tree/master/samples.
Try running the samples and working with them to see if you can resolve your issue. If not, please create an issue containing a complete runnable sample here: https://github.com/oracle/python-cx_Oracle/issues.
answered Nov 19 '18 at 17:44
Anthony TuiningaAnthony Tuininga
3,01421014
3,01421014
I suspect I may be missing something in my import statements. What I have is: "import cx_Oracle" Should I have something more, or different?
– Topher
Nov 20 '18 at 20:26
All you need is import cx_Oracle. Take a look at the samples and you'll see what I mean.
– Anthony Tuininga
Nov 21 '18 at 20:37
I've learned from an unrelated posting that these "errors" are a bug in PyLint. I haven't had time to verify this yet.
– Topher
Nov 22 '18 at 22:37
add a comment |
I suspect I may be missing something in my import statements. What I have is: "import cx_Oracle" Should I have something more, or different?
– Topher
Nov 20 '18 at 20:26
All you need is import cx_Oracle. Take a look at the samples and you'll see what I mean.
– Anthony Tuininga
Nov 21 '18 at 20:37
I've learned from an unrelated posting that these "errors" are a bug in PyLint. I haven't had time to verify this yet.
– Topher
Nov 22 '18 at 22:37
I suspect I may be missing something in my import statements. What I have is: "import cx_Oracle" Should I have something more, or different?
– Topher
Nov 20 '18 at 20:26
I suspect I may be missing something in my import statements. What I have is: "import cx_Oracle" Should I have something more, or different?
– Topher
Nov 20 '18 at 20:26
All you need is import cx_Oracle. Take a look at the samples and you'll see what I mean.
– Anthony Tuininga
Nov 21 '18 at 20:37
All you need is import cx_Oracle. Take a look at the samples and you'll see what I mean.
– Anthony Tuininga
Nov 21 '18 at 20:37
I've learned from an unrelated posting that these "errors" are a bug in PyLint. I haven't had time to verify this yet.
– Topher
Nov 22 '18 at 22:37
I've learned from an unrelated posting that these "errors" are a bug in PyLint. I haven't had time to verify this yet.
– Topher
Nov 22 '18 at 22:37
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53329830%2fpython-django-how-do-i-determine-the-class-to-specify-in-an-except-statement%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
tq8IBSwc63 xoUpWavWGCd1K4kbPMO0rW
cx-oracle.readthedocs.io/en/latest/module.html lists
cx_Oracle.DatabaseError
. Maybe a different "version"? A shadowing module?– user2864740
Nov 16 '18 at 0:48
Thank you for the suggestions. I had previously looked at either this or similar documentation. I would be very astonished if we had a different version of cx_Oracle kicking around, but who knows. I'll have to check tomorrow, when I have access. But the very fact that className is "DatabaseError" indicates that I'm using a version that matches this documentation.
– Topher
Nov 16 '18 at 3:04