Skip to content

Commit 0058e2f

Browse files
feat: add try, catch & finally
1 parent 17c6c5d commit 0058e2f

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
/* INFO: try, catch & finally
2+
1. try: Block of code to test for errors.
3+
2. catch(error): Handles the error object if one is thrown.
4+
3. finally: Runs no matter what - useful for cleanup
5+
*/
6+
7+
// syntax
8+
try {
9+
// code that might throw an error
10+
} catch (error) {
11+
// code that runs if there's an error
12+
} finally {
13+
// Code that always runs, regardless of error
14+
}
15+
16+
// Example
17+
function divide(a, b) {
18+
try {
19+
if (b === 0) throw new Error("Cannot divide by zero!");
20+
return a / b;
21+
} catch (err) {
22+
console.error("Error:", err.message);
23+
return null;
24+
} finally {
25+
console.log("Division attempted.");
26+
}
27+
}
28+
divide(10, 0);

0 commit comments

Comments
 (0)