Python Raise: signal an error on purpose
raise ValueError("message") stops the current code and passes the error up until an except catches it. raise ... from err keeps the original error as the cause.
Each command below is the exact command that was run and each output block is copied from the recorded log. Test ids, log hashes and exit statuses are in the evidence table.
TE-66-A: raise from keeps the original error as __cause__
Setup for this run, inside a throwaway directory (mktemp -d):
cat > s.py <<'EOS'
def parse(s):
try:
return int(s)
except ValueError as err:
raise RuntimeError('bad input') from err
try:
parse('x')
except RuntimeError as e:
print(e)
print(type(e.__cause__).__name__)
EOSCommand:
python3 s.pyRecorded output:
bad input
ValueErrorExit status: 0. The output matches the expected text written before the run.
TE-66-B: a raised ValueError can be caught, and repr shows its type and message
Setup for this run, inside a throwaway directory (mktemp -d):
cat > s.py <<'EOS'
try:
raise ValueError('bad')
except ValueError as e:
print(repr(e))
EOSCommand:
python3 s.pyRecorded output:
ValueError('bad')Exit status: 0. This status and the output match what was written before the run.
TE-66-C: expected non-zero exit: a raised error that nothing catches ends the program with exit status 1
Setup for this run, inside a throwaway directory (mktemp -d):
cat > s.py <<'EOS'
raise ValueError('bad')
EOSCommand:
python3 s.pyRecorded output: none, standard output was empty.
Standard error from the same run:
Traceback (most recent call last):
File "/tmp/b17-myl_9qdo/work/s.py", line 1, in <module>
raise ValueError('bad')
ValueError: badExit status: 1. This status and the output match what was written before the run. The path in the traceback line is a temporary folder and differs on each machine and each run.
TE-66-B: the ValueError was caught, and repr printed ValueError('bad'). TE-66-C: the raised ValueError was not caught. The program ended with exit status 1 and the last line of standard error is ValueError: bad.
Limits
Custom exception classes and finally ordering are not covered by this run.
Source
- https://docs.python.org/3/tutorial/errors.html#raising-exceptions
- https://docs.python.org/3/tutorial/errors.html#exception-chaining
Evidence table
| Test | What it checks | Exit | Verdict | Log sha256 (first 12) | |---|---|---|---|---| | TE-66-A | raise from keeps the original error as __cause__ | 0 | PASS | 3f746006fd82 | | TE-66-B | a raised ValueError can be caught, and repr shows its type and message | 0 | PASS | b727db3cd05a | | TE-66-C | expected non-zero exit: a raised error that nothing catches ends the program with exit status 1 | 1 | PASS | c8b4c56ec151 |
Recorded on: bash 5.1.16(1)-release; git version 2.34.1; Python 3.10.12. Locale C.UTF-8, TZ=UTC. Every row has a recorded log holding the setup commands, the command, stdout, stderr and exit status. The first 12 characters of the log's sha256 are in the table.
All full guides: All guides