-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy patherror-handling.smash
More file actions
80 lines (71 loc) · 1.64 KB
/
error-handling.smash
File metadata and controls
80 lines (71 loc) · 1.64 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
// SmashLang Error Handling Examples
// Basic try-catch
try {
// Code that might throw an error
let x = JSON.parse('{"invalid": json}');
} catch (error) {
print("Caught an error: " + error);
}
// Try-catch-finally
try {
// Code that might throw an error
throw "Something went wrong!";
} catch (error) {
print("Caught an error: " + error);
} finally {
print("This will always execute");
}
// Nested try-catch blocks
try {
print("Outer try block");
try {
print("Inner try block");
throw "Inner error";
} catch (innerError) {
print("Caught inner error: " + innerError);
throw "Rethrown error";
}
} catch (outerError) {
print("Caught outer error: " + outerError);
}
// Custom error handling function
fn handleError(fn) {
try {
return fn();
} catch (error) {
print("Error handled: " + error);
return null;
}
}
// Using the custom error handler
let result = handleError(fn() {
throw "Custom error";
});
print("Result: " + result);
// Conditional error handling
fn divide(a, b) {
if (b === 0) {
throw "Division by zero";
}
return a / b;
}
try {
let result1 = divide(10, 2);
print("10 / 2 = " + result1);
let result2 = divide(10, 0);
print("This line won't execute");
} catch (error) {
print("Caught division error: " + error);
}
// Error objects
try {
throw {
name: "CustomError",
message: "This is a custom error object",
code: 123
};
} catch (error) {
print("Error name: " + error.name);
print("Error message: " + error.message);
print("Error code: " + error.code);
}