// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.7.0 <0.9.0;
// SimpleDivision contract that performs division of two numbers
contract SimpleDivision {
// Function to divide two numbers, requires the second number to be greater than 0
function Divide2Nums(uint256 numone, uint256 numtwo) public pure returns (uint256) {
// Ensure the divisor is not zero to prevent division by zero error
require(numtwo > 0, "numtwo is less than or equal to zero");
// Perform the division and return the result
return numone / numtwo;
}
}
// TryCatchExample contract that demonstrates try-catch functionality with SimpleDivision contract
contract TryCatchExample {
// Instance of the SimpleDivision contract
SimpleDivision sa;
// Event to log results of the division and any error messages
event myevent(uint256 resultOrErrorCode, string message);
// Event to log low-level error data
event mybytes(bytes lowLevelData);
// Constructor that initializes a new SimpleDivision contract instance
constructor() {
sa = new SimpleDivision();
}
// Function to perform division and handle any errors using try-catch
function GetDivision(uint256 a, uint256 b) public returns (bool) {
// Try to perform the division using the Divide2Nums function
try sa.Divide2Nums(a, b) returns (uint256 ab) {
// If successful, emit the result and a success message
emit myevent(ab, "pure success");
return true;
}
// Catch block for require statement failures in the called function
catch Error(string memory reason) {
// Emit the error reason
emit myevent(0, reason);
return false;
}
// Catch block for internal errors (like division by zero) that revert the transaction
catch Panic(uint errorCode) {
// Emit the error code and a failure message
emit myevent(errorCode, "pure failure");
return false;
}
// Catch block for other low-level errors
catch (bytes memory lowLevelData) {
// Emit the low-level error data
emit mybytes(lowLevelData);
return false;
}
}
}