The Importance of Error Handling in C

  Рет қаралды 30,584

Nir Lichtman

Nir Lichtman

Күн бұрын

Error handling is one of the most important things you need to do in order to write good production level C code
You can get the sysinternals suite from the Windows Store or with winget package manager.

Пікірлер: 114
@rocknowradio
@rocknowradio 9 ай бұрын
"That is because C does not come with built-in exception support". Thanks God for that.
@pavfrang
@pavfrang 9 ай бұрын
Your video is GREAT! I would only comment that it would be preferable to print to stderr instead of stdout (printf), for critical errors that terminate the application. So, you should use fprintf(stderr, ...) instead. The main reason for this, is that different redirection is typically done for stderr and stdout - the user might want to handle error messages differently from the informational messages.
@nirlichtman
@nirlichtman 9 ай бұрын
This is a great point, thanks!
@ilmannen
@ilmannen 9 ай бұрын
Another suggestion is to use perror (also prints to stderr), which provides the message from the errno to the user without them having to look it up.
@rian0xFFF
@rian0xFFF 9 ай бұрын
I just use perror()
@blacklistnr1
@blacklistnr1 9 ай бұрын
I've felt the lack of a separate error channel because I thought "just put everything into stdout, so much easier!" in a project: * the stdout quickly became unreadable and broke formatting * it also broke the REPL which was using stdin/out => errors needed special integration to be readable so "just put errors into stderr, so much easier!" :))
@pavfrang
@pavfrang 9 ай бұрын
yep perror the same, I just wanted to emphasize writing to stderr@@ilmannen
@sputnick1
@sputnick1 9 ай бұрын
Great video! this is actually a big issue i certainly had in my first few c programs before i had enough experience to know better. One thing to note is the perror function. If you call perror, not only will it print to stderr (always print to stderr instead of stdout for errors), but it will also give you a description of the error number encountered. (the same text from the errno command)
@johnshaw6702
@johnshaw6702 9 ай бұрын
Thanks for presenting this. One of the things that always botherd me is progaming books that say they are leaving out the error checking to simplify the code for understanding, which it does, was that they often leave out a section on proper error checking and handling. When I first taught myself programming, I did a lot of research and reading (before the internet). I didn't fully trust anything and made sure that if my program failed it didn't crash the system, barring a system/hardware failure. Then modern systems like Windows came out and all bets were off. I could still write good code, but now I was more dependent on the Windowing system to not introduce errors, like memory leaks that forced me to write work arounds.
@uberbaud
@uberbaud 9 ай бұрын
Instead of calling gcc or clang directly, you can call 'make prog' and it will compile prog.c using environment variables CFLAGS LDFLAGS and LDLIBS. No Makefile required. You can see exactly the calls make will use with 'make -p'. One benefit is no a.out, and it's usually less typing.
@erc0re526
@erc0re526 9 ай бұрын
Its amazing that it works. Now I must ask, how did you find this out? I didn't see any mention of it in the manpage... Thank you for this tip!
@uberbaud
@uberbaud 9 ай бұрын
@@erc0re526 In the opening paragraph of OpenBSD's make(1) man page, it says, " If neither of these exist, make can still rely on a set of built-in system rules." One of the many reasons I like OpenBSD is the quality of its documentation. Notably, GNU make has the same behavior but their manpage incorrectly states that "you must write a file called the makefile".
@erc0re526
@erc0re526 9 ай бұрын
@@uberbaud One more reason for me to try OpenBSD! That's fascinating. Thank you
@michaelhohmann2868
@michaelhohmann2868 8 ай бұрын
I really appreciate your focus on important and interesting information. There is no unnecessary spam and begging for likes and subscriptions. I immediately liked and subscribed 8-)
@kinershah464
@kinershah464 4 ай бұрын
So much cool information. Very important error handling, right error handling with right tools and you can avoid hours of debugging an issue.
@alielmessaoudi4863
@alielmessaoudi4863 9 ай бұрын
Very valuable and interesting content, can't stop watching your videos, absolute value here
@imod5
@imod5 9 ай бұрын
I am currently working on an actual c program for the first time and this video showed in my home page at the right time. Thanks!
@johnshaw6702
@johnshaw6702 9 ай бұрын
Check everything unless you know for a fact it can't fail and even then you may want to check. If you're not sure about something, look it up and verify. I self taught myself in the late 80's and early 90's and always double checked everything. Return values are there for a reason. Programmer's mantra: Trust but Verify.
@imod5
@imod5 9 ай бұрын
@@johnshaw6702 That is a very valuable tip. Thank you for sharing!
@mohammedsalman3397
@mohammedsalman3397 9 ай бұрын
If you're on vim you can do shift-K to bring up the manual for the function your cursor is on
@nirlichtman
@nirlichtman 9 ай бұрын
That is a cool tip, thanks! Just notice that it opens on full screen and so if you want to open the manual in split screen you can either use the :term like I do in the video or the :Man vim command which opens the manual as a Vim buffer
@darknais
@darknais 9 ай бұрын
man thats a god hack!! in my coding campus we dont have access to internet during exam only man pages this going to save me some time!
@mohammedsalman3397
@mohammedsalman3397 9 ай бұрын
@@nirlichtman Yeah, forgot that it takes over the entire screen by default 😅I use neovim which opens the man page in a split window which I assume it's not impossible to do in vim.
@anon_y_mousse
@anon_y_mousse 8 ай бұрын
I didn't even know there was an errno program. I thought maybe you wrote it yourself but looked it up and found it in moreutils. I'll have to recommend this to anyone learning C.
@steveoc64
@steveoc64 8 ай бұрын
Be interesting to do a retake of this using zig, as it’s a good demo of how zig applies error handling to existing C idioms, without adding a tonne of boilerplate or weird abstractions. The error backtrace is particularly handy as well.
@acdimalev8405
@acdimalev8405 8 ай бұрын
These days, rather than prototyping without error handling I lean into explicitly terminating the program. void _panic(int line) { printf("PANIC: %d ", line); exit(-1); } #define panic _panic(__LINE__) This helps with finding problems early without littering the program with boilerplate, and later it's useful for identifying places that I may want to add additional error handling logic. As a side bonus, it's also an active deterrant against internalizing an active ignorance of error handling. With how much time I spend prototyping, it's foolish to think it will be easy to mode-switch out of the habits I develop while prototyping.
@meni181818
@meni181818 9 ай бұрын
instead of initializing the whole buffer with zeros you can set the last char of it to zero: #define BUF_LEN 256; char buffer[BUF_LEN]; buffer[BUF_LEN - 1] = '\0'; thanks for your content!
@eitantal726
@eitantal726 9 ай бұрын
Then your buffer is filled with garbage (former stack data) except the last char. You merely ensure that if an un-initialized char buffer is used, it will stop at the end at least. I wouldn't recommend this technique unless CPU time is so critical that "whatever = {0};" is too expensive
@meni181818
@meni181818 9 ай бұрын
@@eitantal726that is the main reason.
@nirlichtman
@nirlichtman 9 ай бұрын
@@eitantal726 I agree with Eitan on this point, it is a good practice to always ensure that you are working with all zeroed buffers or else it can lead to weird bugs
@r3v0lv3rz
@r3v0lv3rz 8 ай бұрын
Very clear and a great explanation of all concepts on your part. Thanks.
@raccoon1160
@raccoon1160 9 ай бұрын
Great video, I see way too much code that just ignores errors. Zero initializing (char buf[256] = {0}) is also standard in C89
@gblargg
@gblargg 9 ай бұрын
Then there's code that lumps all errors together. Disk full? Read-only filesystem? Out of memory? File not found? User value out of range? All the same error reported to the user!
@StefanWelebny
@StefanWelebny 9 ай бұрын
Again valuable content. And thank you very much for answering my question about port connection concurrency regarding your last video!
@UliTroyo
@UliTroyo 9 ай бұрын
Your C videos are so good! Thanks!
@SuborbitalSentinel
@SuborbitalSentinel 9 ай бұрын
Do you have any videos on your dev setup? I'm interested in how you are running what looks like dwm and the windows terminal?
@nirlichtman
@nirlichtman 9 ай бұрын
My welcome link in the channel description contains info about my setup, I also have a video about this on my channel
@grimvian
@grimvian 9 ай бұрын
For a immediately C coder like me, it's a great topic to incorporate error handling the correct C way. And a big thanks for not using music and not using disturbing video editing. May I ask, why you kind of do advertising for a Chinese brand?
@nirlichtman
@nirlichtman 9 ай бұрын
Are you referring to my hostname with "lenovo" in it? that is not part of any advertising on purpose, it's my laptops name for many years, but indeed it is a good idea now to change the name didn't think about this, thanks for the feedback :)
@grimvian
@grimvian 8 ай бұрын
@@nirlichtman Yes I am and just what i thought. Now retired reseller and had installed thousands of Windows computers, by wiped out everything on the hard drive. I just installed a clean system and minimum of drivers. Now it's Linux Mint LMDE and C programming with Code::Blocks. Keep up the great work.
@aah134-K
@aah134-K 9 ай бұрын
Very amazing videos, what a treasure
@Not_Even_Wrong
@Not_Even_Wrong 9 ай бұрын
Thanks. I need to learn more about this, even good books don't convert it at all.
@Jonathan-ru9zl
@Jonathan-ru9zl 6 ай бұрын
Hi Nir. Thanks for the videos 🙌 Do you recommend using Linux over Windows OS?
@nirlichtman
@nirlichtman 6 ай бұрын
Whatever you find most comfortable, I like using Windows as my main OS and Linux through WSL
@Jonathan-ru9zl
@Jonathan-ru9zl 6 ай бұрын
@@nirlichtman I don't get it why people are still using Linux as their main OS (And saying that it is better than Windows)? Let me explain my point of view (Related to Ubuntu mostly): 1. Linux OS is asking for the password every once in a while, approx. 100 times a day, wasting a bunch of time. If you're not lucky, Linux can't detect even the right password Isn't it archaic and stupid? 2. Linux isn't compatible with many software programs and drivers 3. It is a command base OS - you have endless shortcuts and commands which are impossible to remember 4. End of life after couple of years, which requires you to install a new version 5. GUI in Windows is extremely better I'm embedded developer, so I am using Linux only because I have to, but for my daily use, I'm happy with Windows
@nirlichtman
@nirlichtman 6 ай бұрын
@@Jonathan-ru9zl Yah my main reasons for preferring Windows as my main OS is the compatilibilty and that I like the user interface and am very familiar with it, and now that there is WSL there is not really a reason for me to switch to Linux, but i like using Linux distros for server side since they mostly have low hardware requirements and are comfortable for those kind of stuff
@Offdopp
@Offdopp 2 ай бұрын
There's just nothing better than Linux for C development, is all. On Linux you have easy access to your choice of package manager, which will automatically handle any and all dynamically linked libraries. Additionally, software is so much easier to install with this method. Oh, and the filesystem(s), system calls, and kernel are all just better than what Windows has to offer. If you want to write software without learning new things, use MacOS Edit: There's good things to say about the OS as a whole, but both Mac and Linux listen to the Unix philosophy, which makes my life as a developer sooooo much simpler.
@Jonathan-ru9zl
@Jonathan-ru9zl 2 ай бұрын
@@Offdopp Windows gui experience is much better, at least for the average user And today, I think Windows come up with many alternatives for Linux packages and libraries And btw, how do you handle typing your password again and again on Linux?
@gblargg
@gblargg 9 ай бұрын
2:40 Set your command prompt to show when a command failed, and its code. Makes it easier to spot failed commands in interactive sessions.
@cyrilemeka6987
@cyrilemeka6987 8 ай бұрын
How?
@gblargg
@gblargg 8 ай бұрын
@@cyrilemeka6987 See "Bash prompt with the last exit code" (assuming you use Bash).
@m0zart-l3q
@m0zart-l3q 9 ай бұрын
Hi Nir, I watched most of your videos and I liked your projects very much. So I want to learn how do you improved yourself so much in low-level programming.
@nirlichtman
@nirlichtman 9 ай бұрын
Thanks! What helped me the most with learning low level is to make my own projects and play around with various linux/windows api calls, for example one of my projects was a c++ web server that stored messages that i sent it, another thing that helped me was to contribute to open source projects which is a great way to learn how to work with a lot of existing code and to use the debugger effectively.
@Abhishek-pp8ck
@Abhishek-pp8ck 9 ай бұрын
​@@nirlichtmanHello Nir sir, i also want to learn linux/C/Networking, where do i start? do you know any resources....?
@nirlichtman
@nirlichtman 9 ай бұрын
@@Abhishek-pp8ck the best way to learn in my opinion is to make your own projects in c and work with the man pages alongside to learn about the os functions, for example an idea for a networking project in c can be a web server and client, or maybe an online simple game, for a general guide on networking i remember beejs guide to networking as good
@jochen_schueller
@jochen_schueller 8 ай бұрын
Yeah, very important, but can also be done later
@umairmuhammadabbas3929
@umairmuhammadabbas3929 9 ай бұрын
Thanks for sharing this information
@OlliS71
@OlliS71 9 ай бұрын
Better use RAII and Exceptions (here system_error) with C++. Much less work.
@nathanthompson506
@nathanthompson506 9 ай бұрын
this was brilliant. thanks
@niki7968
@niki7968 9 ай бұрын
I have a quick question. Why do you use the windows terminal, or at least riced some other terminal to look like the window's one, on linux? Is it just for the laughs?
@nirlichtman
@nirlichtman 9 ай бұрын
I am using Windows as my main OS and a dwm port for Windows, more info about my setup in the channel description
@darknais
@darknais 9 ай бұрын
Thanks for the video!
@AlaskanInsights
@AlaskanInsights 4 ай бұрын
another good reason is the use of void main.... errrrr
@xBiggs
@xBiggs 9 ай бұрын
void main lul
@nno64209
@nno64209 9 ай бұрын
Can you make a window tutorial with assembly, please ?
@nirlichtman
@nirlichtman 9 ай бұрын
You mean opening a window with Assembly? Or Windows the OS?
@ItsCOMMANDer_
@ItsCOMMANDer_ 9 ай бұрын
Another good example is yohttps srrver video, after the ser er has been used once (at leadt for me) bind() will fail the next time with return code - 1. I dobt want to blame you , this might be a problem with my wsl setup. But without debug printing the return values, i would have never kniwn that bind was the reason the server only works sometimes
@nirlichtman
@nirlichtman 9 ай бұрын
Your comment on that vid was indeed one of my inspirations for making this video :) Bind indeed can fail sometimes if you run it again on the same port not long after the previous run has finished (my guess is that it is due to some OS used ports cleanup that has not happened yet)
@ItsCOMMANDer_
@ItsCOMMANDer_ 9 ай бұрын
most likely true, because errno returns 0.@@nirlichtman
@robertolin4568
@robertolin4568 9 ай бұрын
Without error handlings, we live with the shell scripts.
@greyfade
@greyfade 8 ай бұрын
Why are you printing the errno with printf? Use `perror(3)`. It will print the error string to stderr (which is what you should be doing), so you don't have to use errno on the command line. This is better for users and better for logging.
@nirlichtman
@nirlichtman 8 ай бұрын
Right, totally agree, that was a mistake
@AK-vx4dy
@AK-vx4dy 9 ай бұрын
What are you using with this numerated tabs on top ?
@ayushmaanshrotriya3677
@ayushmaanshrotriya3677 9 ай бұрын
Hey. Can you do a video on c based project like creating heap memory manager??
@sbef
@sbef 9 ай бұрын
Instead of that printf that prints a numeric errno, you can just use perror.
@smylesg
@smylesg 9 ай бұрын
I guess I would start by checking s != -1. No point in building structures or making other calls unnecessarily.
@bigapple89
@bigapple89 9 ай бұрын
Could you make a video on creating a simple email server? Thanks anyway!
@guilherme5094
@guilherme5094 9 ай бұрын
👍👍Thanks!
@otaxhu
@otaxhu 8 ай бұрын
I did not know about errno header file
@NecdetSanli
@NecdetSanli 7 ай бұрын
How did you split your terminal? Do you use vim as editor?
@nirlichtman
@nirlichtman 7 ай бұрын
Yes I use Vim and I split using the built in windowing, for more info I have a video about cool window splitting features on Vim
@its_code
@its_code 9 ай бұрын
❤❤❤❤❤❤😊
@AdventuresOfPepero
@AdventuresOfPepero 9 ай бұрын
wait! wait! you are inside windows?! how did you use dwm inside windows?
@nirlichtman
@nirlichtman 9 ай бұрын
check out the welcome link in the channel description :)
@BSPNode
@BSPNode 9 ай бұрын
Before I get into this, shouldn’t main return an integer? Also I see you dereferencing the “strrchr” function, but I didn’t even know that was possible. Can anyone explain if this is valid C?
@Not_Even_Wrong
@Not_Even_Wrong 9 ай бұрын
You're correct. When I have time I'll compare the assembly and see what or IF the compiler does anything differently. This is why C is so insane... Why not just throw a 'this is wrong learn C' error? No the compiler just does 'something '.... Smh
@nirlichtman
@nirlichtman 9 ай бұрын
Actually, returning void from main is completely valid C :) According to the documentation, since C99 the main entry point can return void and this means the program exit code is undefined devdocs.io/c/language/main_function About the deref of strchr, it also valid C, but as I explain later in the video, it is recommended to check if it failed before derefing it
@BSPNode
@BSPNode 9 ай бұрын
@@Not_Even_Wrong Fair enough, I'm mainly a Windows programmer, so seeing how "void main" is legal confused me a bit. After a minute of research, a lot of the C++ people hate the idea of "void main", and require programmers to use "int main" instead.
@BSPNode
@BSPNode 9 ай бұрын
​@@nirlichtman Learn something new every day :) - I'm mainly a computer graphics programmer, so I don't know how I got here, but great video though!
@Not_Even_Wrong
@Not_Even_Wrong 9 ай бұрын
@@nirlichtman okay it's valid in the sense that unspecified in C means implementation defined. It can always return 0 or 1 or whater BUT the compiler has to decide. In contrast to undefined which means nobody has to decide... This is the part of C that I don't like... Thanks for replying either way. Taught me once again to not trust stackoverflow...
@Benjaneb
@Benjaneb 9 ай бұрын
It looks like you're running dwm on Windows, how is that possible?
@nirlichtman
@nirlichtman 9 ай бұрын
I am using a port for Windows, the welcome link on my channel desc contains additional info
@ryku112
@ryku112 9 ай бұрын
hi how do you find the functions with man,when i try it it doesn't work
@nirlichtman
@nirlichtman 9 ай бұрын
You can get the dev man pages with your package manager, if you are using Debian/Ubuntu you can run apt install manpages-dev, more info about my setup in the channel description link
@ryku112
@ryku112 9 ай бұрын
@@nirlichtman tysm
@styx2084
@styx2084 9 ай бұрын
do you use DWM in windows?
@nirlichtman
@nirlichtman 9 ай бұрын
yes, more info on the welcome link on my channel description
@masterbedroom594
@masterbedroom594 9 ай бұрын
Hi Nir, how are you? Are you safe?
@nirlichtman
@nirlichtman 9 ай бұрын
My country is going through complicated times, but I am safe, thanks
@alister_
@alister_ 9 ай бұрын
@@nirlichtman Where are you from? :\ Wish you the best.
@nirlichtman
@nirlichtman 9 ай бұрын
@@alister_ thanks, I am from israel
@kamertonaudiophileplayer847
@kamertonaudiophileplayer847 9 ай бұрын
Rust uses a similar error handling, but you can skip it, you have to explicitly say - ignore an error.
@swedishpsychopath8795
@swedishpsychopath8795 9 ай бұрын
FAKE TUTORIAL: At 2:27 if you stop the video and microstep back and forth (with dot and comma) you can spot the compile error he didn't want us to see.
@nirlichtman
@nirlichtman 9 ай бұрын
Actually, the tutorial is completely real - that is a compiler warning, not an error (the warning is related to the address structure - this is not related to the point of the video anyway) and I am completely fine with you seeing it, it appears for more than a microstep no need for dot and comma.
@DK1PL
@DK1PL 9 ай бұрын
The Importance of Error Handling in C: I have expected some ideas of sophisticated error handling in C and I found just a basic of the return value handling as on first page of the C language tutorial. 👎
@LabiaLicker
@LabiaLicker 9 ай бұрын
ayo hold up. your seriously using the edge browser? 💀
Making Minimalist Chat Server in C on Linux
14:28
Nir Lichtman
Рет қаралды 42 М.
the cleanest feature in C that you've probably never heard of
8:13
Spongebob ate Patrick 😱 #meme #spongebob #gmod
00:15
Mr. LoLo
Рет қаралды 13 МЛН
Как подписать? 😂 #shorts
00:10
Денис Кукояка
Рет қаралды 7 МЛН
АЗАРТНИК 4 |СЕЗОН 3 Серия
30:50
Inter Production
Рет қаралды 997 М.
Simple error handling in Rust
23:46
Let's Get Rusty
Рет қаралды 32 М.
What is the Smallest Possible .EXE?
17:04
Inkbox
Рет қаралды 395 М.
Arenas, strings and Scuffed Templates in C
12:28
VoxelRifts
Рет қаралды 87 М.
When you Accidentally Compromise every CPU on Earth
15:59
Daniel Boctor
Рет қаралды 824 М.
Vim Tips I Wish I Knew Earlier
23:00
Sebastian Daschner
Рет қаралды 66 М.
How does an OS boot? //Source Dive// 001
50:22
Low Byte Productions
Рет қаралды 414 М.
Gitlab DELETING Production Databases | Prime Reacts
17:27
ThePrimeTime
Рет қаралды 334 М.
Making Minimalist HTTPS Server in C on Linux
16:11
Nir Lichtman
Рет қаралды 18 М.
Making a Very Minimal Windows Executable in C
7:48
Nir Lichtman
Рет қаралды 91 М.
Spongebob ate Patrick 😱 #meme #spongebob #gmod
00:15
Mr. LoLo
Рет қаралды 13 МЛН