[JavaScript] Error Handling
![[JavaScript] Error Handling](https://cdn.hashnode.com/res/hashnode/image/upload/v1681447167506/5b242d07-d2fe-46ef-aa0f-4b3a6e323a98.png)
Error Handling
Error handling is the way of managing errors and dealing with unexpected situations in a software application.
Errors can be categorized into expected errors and unexpected errors, and when designing a typical application, it should be assumed that unexpected error situations are more likely to occur.
There is always a possibility of unexpected errors occurring in code written by programmers, and it is important to be prepared to handle such error situations at any time.
try-catch
To prevent errors from occurring on the server, we implement exception handling.
const users = ["Lee", "Kim", "Park", 2];
try {
for (const user of users) {
console.log(user.toUpperCase());
}
} catch (err) {
console.error(`Error: ${err.message}`);
}
// LEE
// KIM
// PARK
// Error: user.toUpperCase is not a function
throw
When intentionally causing an error
function withdraw(amount, account) {
if (amount > account.balance)
throw new Error("No remaining balance"); // function stops running
account.balance -= amount; // not executed
console.log(`Current balance: ${account.balance}`); // not executed
}
const account = { balance: 1000 };
withdraw(2000, account);
// Error: "No remaining balance"
finally
Executed regardless of whether an attempted write operation throws an error or not
function errorException(isThrow) {
try {
console.log('Resource allocated');
if (isThrow) throw new Error();
} catch (error) {
console.log('Error arised');
} finally {
console.log('Resource deallocated');
}
}
errorException(false);
// Resource allocated
// Resource deallocated - always executed
errorException(true);
// Resource allocated
// Error arised
// Resource deallocated - always executed
![[코테] 그리디 문제 - 무지의 먹방 라이브](https://cdn.hashnode.com/res/hashnode/image/upload/v1712215455263/1ac1f35a-8862-4e42-8d0c-e2bea01e04c0.png)
![[코테] Bfs 토마토](https://cdn.hashnode.com/res/hashnode/image/upload/v1709032619170/70056896-c857-444b-9c99-45bfcb466806.png)
![[코테] Dfs 문제 유형 - 그래프 내에서 구분하여 카운트 하기](https://cdn.hashnode.com/res/hashnode/image/upload/v1709019361383/b0585d72-c808-4169-83a9-2724f312e927.png)
![[코테] DFS vs BFS](https://cdn.hashnode.com/res/hashnode/image/upload/v1708971211123/71f9386c-6a62-43b2-a602-4d084c24d6cf.png)
![[코테] 여행경로](https://cdn.hashnode.com/res/hashnode/image/upload/v1708971251412/27ce72ed-8ee7-4d13-a02f-ff4bbe50c4be.png)