유튜브를 통해, 쉽고 간편하게 이해 해보아요!
구독/좋아요 해주셔서 감사합니다 :) !!
안녕하세요
지난 시간에 이어
2. 외부 스마트 컨트랙을 생성 할 때 try/catch
3. 내부 스마트 컨트랙에서 함수를 부를때 try/catch
try/catch 문을 볼게요.
2. 외부 스마트 컨트랙을 생성 할 때 try/catch
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.7.0 <0.9.0;
contract character{
string private name;
uint256 private power;
constructor(string memory _name, uint256 _power){
name = _name;
power = _power;
}
}
contract runner{
event catchOnly(string _name,string _err);
function playTryCatch(string memory _name, uint256 _power) public returns(bool successOrFail){
try new character(_name,_power) {
return(true);
}
catch{
emit catchOnly("catch","ErrorS!!");
return(false);
}
}
}
}
character와 runner 컨트랙이 있습니다.
저희는 chracter 컨트랙을 try/catch 문으로 생성해보겠습니다.
먼저 character 에는 컨스트럭터 string memory _name 과 uint256 _power 있습니다.
이전과 마찬가지로, runner에 try/catch문에 넣어줄것입니다.
playTryCatch문은 당연히 character에 string memory _name 과 uint256 _power 넣어져야하니, string memory _name 과 uint256 _power 를 파라메터로 받아요.
그러고 나서,
try new character(_name,_power) {
return(true);
}
정의를 해줍니다.
character 가 잘생성이되면 true가 나옵니다
만약에 에러가 나면 catch문에 걸리도록 해야하니 catch문을 정의하겠습니다.
try new character(_name,_power) {
return(true);
}
catch{
emit catchOnly("catch","ErrorS!!");
return(false);
}
이렇게 정의가 되었답니다.
3가지 catch가 아닌 그냥 하나의 catch로도 가능하답니다.
3. 내부 스마트 컨트랙에서 함수를 부를때 try/catch
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.7.0 <0.9.0;
contract runner2{
function simple() public returns(uint256){
return 4;
}
event catchOnly(string _name,string _err);
function playTryCatch() public returns(uint256,bool){
try this.simple() returns(uint256 _value){
return(_value,true);
}
catch{
emit catchOnly("catch","ErrorS!!");
return(0,false);
}
}
}
runner 스마트 컨트랙 하나가 존재합니다.
이 안에는 simple 이라는 4를 리턴하는 함수가 있습니다.
자 인제 이걸 try/catch 문에 넣어 보도록하겠습니다.
try this.simple() returns(uint256 _value){
return(_value,true);
}
catch{
emit catchOnly("catch","ErrorS!!");
return(0,false);
}
여기서 주목해야할점은 "this" 라는 키워드 입니다.
이 this 는 지금 현재 스마트컨트랙을 나타내고 있습니다.
즉 this.simple() 이스마트 컨트랙의 simple 함수 라는 뜻입니다.
이렇게 내부에서 try/catch를 쓰기위해서는 this는 필수적입니다.