Control flow: try-catch or if-else?

Introduction

Scenario

// signUp.js 
function signUp(){ // function of signup
userTable.isUnique(nickname) // Check for duplicate nickname.
duplicateDetailInfo(email, phone); // Check duplicate on personal information.
addUser(user) // Add a user
}

// duplicateDetailInfo.js
function duplicateDetailInfo(email, phone){
userTable.isUnique(email); // Verify email address is unique.
userTable.isUnique(phone); // Verify phone number is unique.
}


// userTable.js
class userTable {
function isUnique(value){
// Will be implemented according to each approach
}
}

On this code, depending on how to implement userTable.isUniqueas Exception or return values(false, null, etc..), I will explain using try-catch and if-else, respectively.

try-catch Exception

// signup.js 
function signUp(){
try {
userTable.isUnique(nickname); // Raise Exception if the nickname is not unique.
duplicateDetailInfo(email, phone); // Check for duplicate personal information.
} catch (e) {
console.log("fail")
}
addUser(user);
}

// duplicateDetailInfo.js
function duplicateDetailInfo(email, phone){
userTable.isUnique(email); // Raise Exception if the email is not unique.
userTable.isUnique(phone); // Raise Exception if the phone is not unique.
}

// userTable.js
class userTable {
function isUnique(value){
value = userDB.find(value);
return !value? true: throw Error(); // Raise Exception if the value is not unique.
}
}
signUp()
├── try
│ ├── .isUnique(nickname)
│ │ └── raise Exception
│ │
│ └── duplicateDetailInfo()
│ ├── .isUnique(email)
│ │ └── raise Exception
│ │
│ └── .isUnique(phone)
│ └── raise Exception

└── catch

if — else

// signup.js 
function signUp(){
if (!userTable.isUnique(nickname)) { // Return false if the nickname is not unique.
return console.log("fail")
}
if(!duplicateDetailInfo(email, phone)) { // Return false if the details is not unique.
return console.log("fail")
};
addUser(user);
}

// duplicateDetailInfo.js
function duplicateDetailInfo(email, phone){
if(!userTable.isUnique(email)) { // Return false if the email is duplicated.
return false;
}
if(userTable.isUnique(phone)) { // Return false if the phone is duplicated.
return false;
};
return true
}

// userTable.js
class userTable {
function isUnique(value){
value = userDB.find(value);
return value? true: false; // Return false if the value is not unique.
}
}
signUp()
├── .isUnique(nickname)
│ └── return false? => handling error

└── duplicateDetailInfo()
└── return false? => handling error

Conclusion

--

--

I primarily write about solving problems about computer engineering and personal stories.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Juhee Kang

I primarily write about solving problems about computer engineering and personal stories.