File tree Expand file tree Collapse file tree 3 files changed +23
-3
lines changed Expand file tree Collapse file tree 3 files changed +23
-3
lines changed Original file line number Diff line number Diff line change
1
+ # Examples
2
+
3
+ This project includes the following two examples:
4
+
5
+ - [ ` print_hex.cpp ` ] ( ./print_hex.cpp ) :
6
+ Prints the hexadecimal representation of the given number.
7
+ This code returns an error if the provided input is not a number.
8
+ This example demonstrates the basic flow of error handling and how to return an error object from a function.
9
+
10
+ - [ ` read_file.cpp ` ] ( ./read_file.cpp ) :
11
+ Reads a file from the given path and prints its content.
12
+ This code returns an error if it fails to open the file.
13
+ This example illustrates the same error handling flow but with examples of how to create an error object with a formatted message.
Original file line number Diff line number Diff line change 1
1
#include < errors/error.hpp>
2
2
#include < iostream>
3
3
4
+ // Prints the hexadecimal representation of the given number string.
4
5
errors::Error print_hex (const char * number_str) {
5
6
int number = std::atoi (number_str);
6
- if (number == 0 ) {
7
+ if (number_str[0 ] != ' 0' && number == 0 ) {
8
+ // The given string is not a number, return an error.
7
9
return errors::make (" is not a number" );
8
10
}
9
11
12
+ // Print the number and return nil.
10
13
std::cout << std::hex << number << std::endl;
11
14
return errors::nil ();
12
15
}
@@ -17,6 +20,7 @@ int main(int argc, char **argv) {
17
20
return 1 ;
18
21
}
19
22
23
+ // Call the function and handle the error.
20
24
const auto err = print_hex (argv[1 ]);
21
25
if (err) {
22
26
std::cerr << err << std::endl;
Original file line number Diff line number Diff line change 2
2
#include < errors/format.hpp>
3
3
#include < fstream>
4
4
5
+ // Reads the file from the given path and prints the contents.
5
6
errors::Error read_file (const char * filepath) {
6
7
std::ifstream file (filepath);
7
8
if (!file.is_open ()) {
8
- return errors::format (" failed to open `{}` ({})" , filepath, static_cast <int >(file.rdstate ()));
9
+ // Unable to open the file, return an error.
10
+ return errors::format (" failed to open '{}' ({})" , filepath, static_cast <int >(file.rdstate ()));
9
11
}
10
12
13
+ // Print the file contents and return nil.
11
14
std::string line;
12
15
while (std::getline (file, line)) {
13
16
fmt::print (" {}\n " , line);
14
17
}
15
-
16
18
return errors::nil ();
17
19
}
18
20
@@ -22,6 +24,7 @@ int main(int argc, char **argv) {
22
24
return 1 ;
23
25
}
24
26
27
+ // Call the function and handle the error.
25
28
const auto err = read_file (argv[1 ]);
26
29
if (err) {
27
30
fmt::print (stderr, " {}\n " , err);
You can’t perform that action at this time.
0 commit comments