I have simple go program where i assign a value to variable like
var sum uint8 = -20
In this code error will be there. Is there any way i can handle that error ?
which kind of error you are talking about ?
like value overflow error
@luk4z7, Appreciate you help i just gave an example with value overflow.
I wanted to know how to handle unknown exceptions that might occur during runtime.
OK, so, I think that you can try the recover, check this
https://medium.com/technofunnel/error-handling-in-golang-with-panic-defer-and-recover-d77db7ae3875
https://go.dev/blog/defer-panic-and-recover
There is run time and compile time errors, you can only recover run time panic errors.
This isn’t exactly what you asked about, but if you want to detect overflows:
-
For smaller integer types like (u)int8, 16 and 32, a common method is to perform the arithmetic in the next largest integer size (e.g. use
int16
to calculate addition of twoint8
s) and check if the result is greater or less than the smaller type’s max/min. -
For the largest Go integer data type:
uint64
, you can use theAdd64
function from themath/bits
package which returns acarryOut
parameter with the resulting overflow.