Error in subtract Nat type

I have a function that performs subtraction but panics with an error

Panicked at 'Cannot subtract b from a because b is larger than a.', /home/abc/.cargo/registry/src/index.crates.io-6f17d22bba15001f/num-bigint-0.4.6/src/biguint/subtraction.rs:69:5, error code None

The problem is that the function panics but executes the next line which depends on subtraction and that is why I printed the logs below. Because the current function test fails but the sub-sequent test pass successfully.


> Code

 add_execution_logs(
            format!("  Amount- Fee {} - {} ", current_amount.clone(), fee.clone()),
        );

let new_amount: Nat = if current_amount.clone() > fee.clone() {
            current_amount.clone() - fee.clone()
        } else {
            return (format!(
                "Amount- Fee {} - {} ",
                current_amount.clone(),
                fee.clone()
            ));
        };

> Logs

{ message: '  Amount- Fee 1_000_000_000 - 100_000 ' }

Candid crate

Code immediately after a panic is definitely not executed. It's an important guarantee of panics.

There may be code running in destructors, and you may see log messages flushed that were buffered before.

Also, panic on arithmetic errors is not guaranteed to happen – in release mode it will wrap unless you re-enable checked arithmetic. Where handling of overflow is important, you should be using .checked_sub() and similar instead of -.

3 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.