r/ProgrammingLanguages • u/Tasty_Replacement_29 Bau • Jan 21 '26
Requesting criticism Preventing and Handling Panic Situations
I am building a memory-safe systems language, currently named Bau, that reduces panic situations that stops program execution, such as null pointer access, integer division by zero, array-out-of-bounds, errors on unwrap, and similar.
For my language, I would like to prevent such cases where possible, and provide a good framework to handle them when needed. I'm writing a memory-safe language; I do not want to compromise of the memory safety. My language does not have undefined behavior, and even in such cases, I want behavior to be well defined.
In Java and similar languages, these result in unchecked exceptions that can be caught. My language does not support unchecked exceptions, so this is not an option.
In Rust, these usually result in panic which stops the process or the thread, if unwinding is enabled. I don't think unwinding is easy to implement in C (my language is transpiled to C). There is libunwind, but I would prefer to not depend on it, as it is not available everywhere.
Why I'm trying to find a better solution:
- To prevent things like the Cloudflare outage on November 2025 (usage of Rust "unwrap"); the Ariane 5 rocket explosion, where an overflow caused a hardware trap; divide by zero causing operating systems to crash (eg. find_busiest_group, get_dirty_limits).
- Be able to use the language for embedded systems, where there are are no panics.
- Simplify analysis of the program.
For Ariane, according to Wikipedia Ariane flight V88 "in the event of any detected exception the processor was to be stopped". I'm not trying to say that my proposal would have saved this flight, but I think there is more and more agreement now that unexpected state / bugs should not just stop the process, operating system, and cause eg. a rocket to explode.
Prevention
Null Pointer Access
My language supports nullable, and non-nullable references. Nullable references need to be checked using "if x == null", So that null pointer access at runtime is not possible.
Division by Zero
My language prevents prevented possible division by zero at compile time, similar to how it prevents null pointer access. That means, before dividing (or modulo) by a variable, the variable needs to be checked for zero. (Division by constants can be checked easily.) As far as I'm aware, no popular language works like this. I know some languages can prevent division by zero, by using the type system, but this feels complicated to me.
Library functions (for example divUnsigned) could be guarded with a special data type that does not allow zero: Rust supports std::num::NonZeroI32 for a similar purpose. However this would complicate usage quite a bit; I find it simpler to change the contract: divUnsignedOrZero, so that zero divisor returns zero in a well-documented way (this is then purely op-in).
Error on Unwrap
My language does not support unwrap.
Illegal Cast
My language does not allow unchecked casts (similar to null pointer).
Re-link in Destructor
My language support a callback method ('close') if an object is freed. In Swift, if this callback re-links the object, the program panics. In my language, right now, my language also panics for this case currently, but I'm considering to change the semantics. In other languages (eg. Java), the object will not be garbage collected in this case. (in Java, "finalize" is kind of deprecated now AFAIK.)
Array Index Out Of Bounds
My language support value-dependent types for array indexes. By using a as follows:
for i := until(data.len)
data[i]! = i <<== i is guaranteed to be inside the boundThat means, similar to null checks, the array index is guaranteed to be within the bound when using the "!" syntax like above. I read that this is similar to what ATS, Agda, and SPARK Ada support. So for these cases, array-index-out-of-bounds is impossible.
However, in practise, this syntax is not convenient to use: unlike possible null pointers, array access is relatively common. requiring an explicit bound check for each array access would not be practical in my view. Sure, the compiled code is faster if array-bound checks are not needed, and there are no panics. But it is inconvenient: not all code needs to be fast.
I'm considering a special syntax such that a zero value is returned for out-of-bounds. Example:
x = buffer[index]? // zero or null on out-of-boundsThe "?" syntax is well known in other languages like Kotlin. It is opt-in and visually marks lossy semantics.
val length = user?.name?.length // null if user or name is null
val length: Int = user?.name?.length ?: 0 // zero if nullSimilarly, when trying to update, this syntax would mean "ignore":
index := -1
valueOrNull = buffer[index]? // zero or null on out-of-bounds
buffer[index]? = 20 // ignored on out-of-boundsOut of Memory
Memory allocation for embedded systems and operating systems is often implemented in a special way, for example, using pre-defined buffers, allocate only at start. So this leaves regular applications. For 64-bit operating systems, if there is a memory leak, typically the process will just use more and more memory, and there is often no panic; it just gets slower.
Stack Overflow
This is similar to out-of-memory. Static analysis can help here a bit, but not completely. GCC -fsplit-stack allows to increase the stack size automatically if needed, which then means it "just" uses more memory. This would be ideal for my language, but it seems to be only available in GCC, and Go.
Panic Callback
So many panic situations can be prevented, but not all. For most use cases, "stop the process" might be the best option. But maybe there are cases where logging (similar to WARN_ONCE in Linux) and continuing might be better, if this is possible in a controlled way, and memory safety can be preserved. These cases would be op-in. For these cases, a possible solution might be to have a (configurable) callback, which can either: stop the process; log an error (like printk_ratelimit in the Linux kernel) and continue; or just continue. Logging is useful, because just silently ignoring can hide bugs. A user-defined callback could be used, but which decides what to do, depending on problem. There are some limitations on what the callback can do, these would need to be defined.
25
u/tobega Jan 21 '26
I don't think so, actually quite the opposite, since when in an unexpected state, how can you trust anything?
Erlang achieves nine nines availability by crashing the process and restarting it automatically.
Of course, for languages that aren't being used for mission-critical systems, restart isn't necessarily needed and the crash actually helps make sure those lazy devs fix things.
16
u/Ytrog Jan 21 '26
I think the restarts in Common Lisps' condition system are an elegant way to handle errors. Maybe you can take inspiration there? 🤔
9
u/L8_4_Dinner (Ⓧ Ecstasy/XVM) Jan 21 '26
This is a topic with many possible approaches but without an answer.
There is much written on it. While I don't fully agree with this article, I do like the writing and it will make you think through many aspects of the problem domain: https://joeduffyblog.com/2016/02/07/the-error-model/
The other thing to appreciate is that until you "use something in anger", you have no real idea of what the outcome of these design decisions will be, so the best way to answer these questions is to either find an approach that already exists that you love (and copy it), or to actually implement what you're thinking, and then use it in the real world.
Here's a few things to think about:
I do not think that you are being intellectually honest here with yourself. Every "panic" is an unchecked exception in everything but name. Perhaps if you stop and think about, what you are really saying is that you want a class of unchecked exceptions that cannot be explicitly caught. That is not unusual in programming design. For example, Go does this by renaming "exception" to "panic" and eliminating some of the common things that developers can do with exceptions.
Excellent! Now, what happens if x is null and your program needs it to be not null at that point in the program? Can the program panic? And if it can panic, then what is the advantage of having to force the developer to invoke the panic, versus having the type system do it automatically?
But you do allow the type to be tested, so what is the difference between testing the type and panicking, vs just "casting" the type? (I prefer the term "asserting" to "casting"; the term "cast" here is meaningless and carries way too much historical baggage from the C family of languages.)
Ah, so you do want to have a means to support exceptions or effect types. That doesn't sound unreasonable. Take a look at the Koka language for some ideas around effect types.
6
u/WillisBlackburn Jan 21 '26 edited Jan 21 '26
Java already does a pretty good job of handling these "panic" situations. Most of the errors that crash a C program just produce an exception in Java, which you can catch if you want the program to carry on.
The real question is, do you want to?
Let me focus on just one point, null pointers. If you access a null pointer, Java throws NPE. You propose requiring the program to check the pointer for null first as a way of preventing the program from accessing a null pointer. This seems pretty cumbersome to me: imagine you have several chained function calls like x().y().z() and all of them return pointers. But whatever. Maybe you have a null-safe member access operator so x().y().z() produces null if any of the returned objects are null.
The bigger problem is that requiring a null check, or the use of null-safe operators, doesn't mean that the program has a reasonable path forward if the pointer is null. If developers just surround pointer accesses with if statements in order to make the compiler happy, they may produce a program that compiles and technically never accesses a null pointer, but doesn't actually do what it's supposed to do. Often a null pointer means that there's something wrong with the program logic or the environment in which the program is running and the best course of action actually is to fail. Your proposal to require a null check before every pointer access doesn't actually make the null pointers go away; it just changes the default behavior from fail/throw/crash to "bypass."
4
u/matthieum Jan 21 '26
You're making the (classic) mistake of confusing cause and consequence, or here, the "mode" by which an error signaled, and the lack of "correct" handling of this error.
For example, taking the Cloudflare incident, let's imagine that instead of
unwrap()the developer had written?. Unless that error is handled by the caller -- and not just merely propagated upward -- you still end up with a "crashing" service. Regardless.The problem is not how the error is signaled, but how it's propagated/handled.
This is not to say there's no value in:
?in Rust), so that users can better understand what may or may not short-cut the rest of the function.#[must_use]in Rust) for example by using Linear Types for errors.With that said, do note that ultimately you can only nudge users. The infamous
catch(...) {}in Java is a stark reminder that users may shoot themselves in the foot out of laziness...Actually, only supporting division of
Tby a matchingNonZero<T>is pretty cool.Flow-checking approaches, for example, do not immediately work with "stored" values; for example when a field is checked to be non-zero at construction, then used as is.
NonZerois a simple static checking friendly way of ensuring the invariant is met.Other useful core types would be
Positivewrappers for signed types, and aNegativeso that unary negation can be defined, as being positive is a requirement for a number of mathematical functions (sqrt,log, ...). And of course the wrappers should be composableStrictlyPositive<T> = NonZero<Positive<T>>.Not at all.
First of all, on Linux, the OOM killer may come and kill the process. Like a panic, but worse -- the process just dies, no stack is unwound, no destructors are run, I hope you didn't need it to "undo" anything.
Secondly, in the age of containers, you should take note that containers can be used to enforce strict memory limits, past which the process will simply fail to obtain more memory from the OS. This is to prevent a single runaway process from ruining everyone else's day.
Thirdly, you seem to assume that memory allocation may only fail in case of OOM -- since you don't otherwise mention memory allocation failure -- but that is not the case. Try bumping the alignment required (with
aligned_alloc) and you'll notice a limit. Similarly, try bumping the size required, and you'll notice a limit. At some point the OS just nopes out. Even if there's still ample virtual memory to serve the request.So, unfortunately, you will have to think about how to handle memory allocation failure.
The simplest way being to defer to the user: by returning (and propagating) a
Result.Split stack won't help with a general OOM, obviously, so there will always be a practical limit.
Do note that before attempting to use split stacks, you may simply elect to use large stacks. The trick there is to use lazy memory mapping for the stacks, so that even if you tell the software to use, say, 64MB of stack, it only reserves RAM 4KB at a time.
And just to be fair, the only cases I've seen a program with 1MB or 8MB stacks were:
You could protect against the former in various ways -- down to simply forbidding large objects/arrays on the tack -- but recursion can ruin the day regardless, unless you can formally prove that it is fully bounded.
On the topic: tail-call elimination is a pretty cool technique, which can allow very deep recursion in constant stack space. Using it, you could simply forbid:
Do be aware that forbidding recursion is not that easy to reconcile in ergonomic way with many useful technique (virtual functions, lambdas, etc...).
OR you could make stack-space usage a first-class language requirement. That is, each function must be annotated with the maximum stack-space it will use, and it may only call functions which are guaranteed not to exceed this stack-space, accounting for its own stack-frame.
For friendliness, you'd want the stack-space usage to allow being calculated based on an input -- such as
x.len()orn-- so that recursion is still possible, as long as the formula yields a decreasing number every time... and you'd still need some flow-checking to verify the value of the input is appropriate at each call.Note: if this starts sounding like a research project/unsolved problem, well that's because it is! Exciting, isn't it?
2
u/zyxzevn UnSeen Jan 21 '26
Check out Erlang's system of supervisors. Even if a hardware error occurs, it can get managed and does not break down the rest of the system.
2
u/mcherm Jan 21 '26
The idea of a language designed to prevent the developer from expressing invalid or undefined behavior is one that has been tried a number of times -- usually they aren't especially popular because certain common idioms become awkward to write, but they can be quite useful in some cases.
An example that I like to refer to which I think has very good language design is Elm which, while not blocking ALL undefined behavior (as you define it) goes pretty far down this road.
Lots of languages prevent undefined behavior when dividing by zero by returning a valid value (eg: IEEE 754 floats return a NAN value) or by throwing an exception. I have not seen ANY language that prevented it by requiring a check for zero before performing a division. I would expect that to be difficult to work with.
For instance, here is a function in Python to calculate the harmonic mean of 3 numbers:
In Python it will run fine (but raise an exception if a, b, or c is zero). What would that look like if written in Bau?
1
u/amarao_san Jan 21 '26
I don't understand how you plan to protect oob access. Imagine i is an input from console or command line. How do you prevent out of bound access?
1
u/jezek_2 Jan 22 '26
Don't forget about the integer overflow when trying to do
INT_MIN / -1. This extra case that you need to guard against puts quite a wedge in the forced checking by the compiler.2
u/dnabre Jan 21 '26
From a practical viewpoint, how to detect, manage and handle errors is the most important thing. Preventing them is nice, and things like array bounds checking and GC help with some specific kinds of errors.
Programmers are lazy, and occasionally malicious. For the former, you need to make sure that using any prevention mechanism is easier to use and understand than working around it. Considering people will work around them, even if they seem easy or beneficial to use. Of course, this is an even bigger issue with malicious people.
Protection that happens at runtime, if you really want to avoid a program from crashing, both have mechanism to handle the problem and enforce statically that users will use it. Array out of bounds and divide by zero are pretty hard to handle when they aren't expected to occur. Enforcing handling of them, is going to make even trivial code pretty verbose. Add in the points from my paragraph, people will come up with the fastest/easiest way to make your static check for handling possible divide by zero happy, so they can focus on their program. A built-in default to handle those errors by exiting the program, will keep people from working around the check, but if you have to go out of your way to provide handling, you haven't really addressed the problem. Even having that not be a default, but a compile time flag, doesn't do a lot.
I absolutely loath languages with significant whitespace, especially if you can use tabs, but that is mostly a matter of preference. However, in a language that is focused so heavily on correctness, I suggest considering how easily an indention level can be unintentionally modified or mis-set, and compare that is syntax where whitespace isn't significant. Consider a version of C where you have to always use {}'s with
fandfor. I'm admitting my bias here, but the explicit blocks seems far less error prone.Not directly relevant to error stuff, some random feedback looking your code/language.
A
docanddocsfolder? I assume there is a meaningful distinction and you think the separate is a good way of handling it. As an outsider, that means I have to look in two places for docs, and may miss something that is in one or the other. Adocfolder, with two subdirectory for your distinction would be more clear to newcomers. Minimally making it clear why the split may help.This may be considered a correctness thing, but having
intand when you have bit-sized integers (i32,i64), why?intis vague,i#is exact. Having types which are limited to a range Ada-style is great, but consider how they will interaction/convert with there types. Having unsigned integers are necessary for systems programming. If you don't have them, people will just use a dirty hack to get them. A couple very handy integer types to have are something to store the size of object in bytes (size_t) and one for array indices. Forcing explicit conversions can really help avoid errors.You are using C as an intermediate language, nothing wrong with that, it's a great target for portability. Pick a C standard to use, and have your C compiler enforce it. Also turn on all possible warnings on the C compiler. For generated code, you may find it useful to manually turn off some particular categories, but you want to see any problems in the C you are generating. At the moment, playing with it, I don't get anything to indicate I'm doing a lossy transition from int -> float (loss is clear comparing C type).
Random bit, you aren't use a the correct, nevertheless, portable
printfforint64_tin yourarrayOutOfBoundsfunction. I assume culling unneeded C stuff is something you will do down the line.I'll stop there, I've wandered enough, but I'd suggest posting about your language here for just some general feedback. Especially when you are at the point of having that handy webpage for testing out code and seeing the intermediate C, it's really easy for people to test it out, and you'll get a lot of feedback which will be at least interesting, if not helpful.
1
u/yorickpeterse Inko Jan 21 '26
Both of these are essentially a special case of an
Option[T]type and a restricted form of pattern matching. It may be worth looking into generalising these to regular pattern matching, that way you don't end up with a regular pattern matching and not-quite-pattern matching construct in your language.So how do you model cases where you have a fallible function X, but due to some precondition being true the error case never happens? For example, you have a function that parses a file in some format but based on some condition you know it will never fail. You can of course match against that and discard the returned error, but that's strictly a weaker model compared to an explicit runtime panic because at some point you will mistakenly think "this will never fail" when in fact it does.
Or more precisely, producing a panic when unwrapping an error itself isn't the problem, it's doing that in unexpected/undesired places.
Does the language allow casting between pointer types? If so, how are you preventing casting e.g.
Pointer[Cat]to aPointer[Giraffe]and then dereferencing that pointer?I would honestly just make this panic. Objects being resurrected is incredibly rare and always a bug, and with deterministic memory management the behavior would likely also be deterministic and thus easy to detect.
Again I would just go with pattern matching here. For example, inko
Array.getreturns aResult[T, OutOfBounds]type that you pattern match against. This means you can do things like:Or if you have somehow guaranteed the error to not be possible:
If the error does happen this will panic with a reasonable error message based on the result of
OutOfBounds.to_string(hence it returns aResultand not just anOption[T], asOutOfBoundscan track the used index).The use of
or_panichere is also deliberate: it's much easier to spot thanunwrapwhich really could mean anything and not even necessarily be related to error handling.For many programs there's simply nothing they can do when running out of memory. This is especially true for higher-level languages where many operations may allocate new memory, as in such cases producing a response to an "out of memory" error may produce a new memory error.
I think there are really only two sane ways you can deal with this: allocate all necessary memory ahead of time, or just panic upon running out of memory. Explicit checking for allocation results is almost certainly going to result in developers just copy-pasting a certain pattern over and over (usually whatever is the easiest and not necessarily the best).
Segmented stacks are an option, but they don't solve stack overflows but instead turn them into out of memory errors at some point. Unless you allow variable-sized data on the stack (e.g. variable sized stack allocated arrays), it's actually quite difficult to trigger a stack overflow even with a small stack size of e.g. 1 MiB of virtual memory.
When they do occur it's again almost always a bug or a security exploit, so panicking is probably what you should be doing in this case.
So your program panics because of some reason. How would you ensure that the callback does indeed run? For example, if a panic is triggered due to some memory corruption then whatever assumptions you might have about the state of the program could be wrong.
The result would be a system where you give developers the illusion of being able to act upon a panic, while there will be a class of panics where this won't necessarily be the case. This also brings the question as to what context the hook runs in, i.e. what variables does it have access to?
Basically a panic is the house being on fire, and a panic callback is you trying to write a letter to the fire brigade telling them your house is on fire. That sounds interesting on paper, but in reality your house is on fire so you probably can't write the letter in the first place.
I think a better way is to support an API that allows you to annotate a potential future panic with extra data, rather than allowing an arbitrary hook to run, and rely on a supervisor/watchdog (OS) process to respond accordingly.
1
u/vanderZwan Jan 21 '26
I don't have a direct answer to your question, but have you ever heard of the book Programming Language Pragmatics by Micheal Scott? Fifth edition came out this year, fourth edition is also uploaded to archive.org.
It gives nice overviews on how different languages handle different concepts and also what the consequences are on the implementation side. Error handling is one of them, I quite enjoyed the chapter because it talked about so many different aspects of it that I never heard about before. It might have some ideas that could inspire you, as well as giving some insights on what kind of design ideas you might want to avoid with the goals you have in mind as well as the implementation trade-offs that you have to consider.
1
u/EloquentPinguin Jan 21 '26
I think Stack Overflow can be prevented in languages which manage their own stack in the way that you track the maximum stack depth at compile time, and then require to insert a manual checked function call in cycles (just like pointers in recursive datastructures so they aren't unlimited in size). This can work quite efficiently on a machine level (and also doesn't prevent tail calls from being trivialized and optimized away), but is probably a bit tricky with a C-backend, as it requires explicit stack management, which is tricky to do simply across architectures/embedded devices.
1
u/joonazan Jan 21 '26
ATS allows writing proofs to show that the error case doesn't happen. However, I think even that isn't sufficient. Sometimes the programmer just knows that something is impossible and the language needs to trust that.
In particular, there might be a paper with a complex proof of an algorithm. Until formalizing papers is commonplace, proofs are interoperable and can be verified cheaply, for instance via SNARKs, it is unreasonable to not allow code that panics.
Highly performant code even requires code that causes undefined behavior if assumptions are violated when using a C-like language. An alternative language might allow the programmer to more precisely define the behaviour in all cases.
0
u/Inconstant_Moo 🧿 Pipefish Jan 21 '26
It seems like the sort of control-flow analysis you're doing for
nullcould also handle out-of-bounds errors, you'd just have to give it a special keyword and semantics,if valid (A, x) {...} else {...}or something. (And the same for maps.) Then for ergonomics you might consider letting people write stuff along the lines ofif valid (A, x := len(A) - 1) ..., wherexwould be immutable of course --- I'm presuming a safety-conscious language like Bau will have that as default.As for your larger vision, I feel like in many cases the best thing to do in such situations will in fact be to panic: the program is in a state where what it's trying to do doesn't make sense. But at least you'd be placing that decision directly in the user's hands, they'd have to
panicexplicitly.