cardinal_pythonlib.exceptions
Original code copyright (C) 2009-2022 Rudolf Cardinal (rudolf@pobox.com).
This file is part of cardinal_pythonlib.
Licensed under the Apache License, Version 2.0 (the “License”); you may not use this file except in compliance with the License. You may obtain a copy of the License at
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an “AS IS” BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
Functions for exception handling.
- cardinal_pythonlib.exceptions.add_info_to_exception(err: Exception, info: Dict) None [source]
Adds an information dictionary to an exception.
- cardinal_pythonlib.exceptions.die(exc: Exception | None = None, exit_code: int = 1) NoReturn [source]
It is not clear that Python guarantees to exit with a non-zero exit code (errorlevel in DOS/Windows) upon an unhandled exception. So this function produces the usual stack trace then dies with the specified exit code.
See https://stackoverflow.com/questions/9555133/e-printstacktrace-equivalent-in-python.
Test code:
import logging import sys import traceback logging.basicConfig(level=logging.DEBUG) log = logging.getLogger() def fail(): try: x = 1/0 except Exception as exc: die(exc)
Then call
fail()
… which should exit Python; then from Linux (for example):
echo $? # show exit code
- cardinal_pythonlib.exceptions.recover_info_from_exception(err: Exception) Dict [source]
Retrives the information added to an exception by
add_info_to_exception()
.