Skip to content

Commit 86cbc2e

Browse files
committed
Fix exception stack
1 parent e5d0a02 commit 86cbc2e

File tree

3 files changed

+30
-7
lines changed

3 files changed

+30
-7
lines changed

tests/snippets/try_exceptions.py

+18
Original file line numberDiff line numberDiff line change
@@ -220,3 +220,21 @@ def y():
220220
raise NameError
221221
except NameError as ex:
222222
assert ex.__context__ == None
223+
224+
225+
try:
226+
{}[1]
227+
except KeyError:
228+
try:
229+
raise RuntimeError()
230+
except RuntimeError:
231+
pass
232+
233+
234+
try:
235+
try:
236+
raise ZeroDivisionError
237+
except ZeroDivisionError as ex:
238+
raise NameError from ex
239+
except NameError as ex2:
240+
pass

vm/src/frame.rs

+8-7
Original file line numberDiff line numberDiff line change
@@ -752,7 +752,7 @@ impl Frame {
752752
_ => vm.get_none(),
753753
};
754754
let exception = match argc {
755-
0 => match vm.pop_exception() {
755+
0 => match vm.current_exception() {
756756
Some(exc) => exc,
757757
None => {
758758
return Err(vm.new_exception(
@@ -767,7 +767,7 @@ impl Frame {
767767
};
768768
let context = match argc {
769769
0 => vm.get_none(), // We have already got the exception,
770-
_ => match vm.pop_exception() {
770+
_ => match vm.current_exception() {
771771
Some(exc) => exc,
772772
None => vm.get_none(),
773773
},
@@ -891,7 +891,7 @@ impl Frame {
891891
bytecode::Instruction::PopException {} => {
892892
let block = self.pop_block().unwrap(); // this asserts that the block is_some.
893893
if let BlockType::ExceptHandler = block.typ {
894-
assert!(vm.pop_exception().is_some());
894+
vm.pop_exception().expect("Should have exception in stack");
895895
Ok(None)
896896
} else {
897897
panic!("Block type must be ExceptHandler here.")
@@ -983,7 +983,7 @@ impl Frame {
983983
}
984984
}
985985
BlockType::ExceptHandler => {
986-
vm.pop_exception();
986+
vm.pop_exception().expect("Should have exception in stack");
987987
}
988988
}
989989
}
@@ -1009,7 +1009,7 @@ impl Frame {
10091009
}
10101010
},
10111011
BlockType::ExceptHandler => {
1012-
vm.pop_exception();
1012+
vm.pop_exception().expect("Should have exception in stack");
10131013
}
10141014
}
10151015

@@ -1057,8 +1057,9 @@ impl Frame {
10571057
}
10581058
}
10591059
BlockType::Loop { .. } => {}
1060-
// Exception was already popped on Raised.
1061-
BlockType::ExceptHandler => {}
1060+
BlockType::ExceptHandler => {
1061+
vm.pop_exception().expect("Should have exception in stack");
1062+
}
10621063
}
10631064
}
10641065
Some(exc)

vm/src/vm.rs

+4
Original file line numberDiff line numberDiff line change
@@ -1014,6 +1014,10 @@ impl VirtualMachine {
10141014
pub fn pop_exception(&self) -> Option<PyObjectRef> {
10151015
self.exceptions.borrow_mut().pop()
10161016
}
1017+
1018+
pub fn current_exception(&self) -> Option<PyObjectRef> {
1019+
self.exceptions.borrow().last().map(|x| x.clone())
1020+
}
10171021
}
10181022

10191023
impl Default for VirtualMachine {

0 commit comments

Comments
 (0)