솔리디티 깨부수기 - 기본
솔리디티 강좌 28강 - 에러 핸들러 4 try/catch 2
D_One
2021. 9. 27. 10:07
유튜브를 통해, 쉽고 간편하게 이해 해보아요!
https://youtu.be/IJffDPqcW3c
구독/좋아요 해주셔서 감사합니다 :) !!
안녕하세요
지난 시간에 이어
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);
}
}
}