Godot Version
v4.2.2.stable.flathub [15073afe3]
Question
Hello, I am moving this post from Reddit because I do not have enough karma to post on r/godot. Everything below is copied and pasted from Reddit, sorry for the trouble
Hello, this is my first post so sorry if it is somewhat ignorant…
I am working on a game with Godot and GDScript. There is a part of my code where I want error handling, because it has a lot of logic and validation, since GDScript doesn’t have a native exception type I decided to use a trick I first learned from Golang. I wrote my code like this:
class Error:
var message: String
func _init(message: String):
self.message = message
static func div(a: int, b: int):
if b == 0:
return Error.new("divide by 0")
return a / b
static func approx_area(radius: int):
var approx_pi = div(339, 108)
if approx_pi is Error:
return approx_pi
return approx_pi * radius * radius
You can see how it is similar to the equivalent Go code:
func ApproxArea(radius int) (int, error) {
approxPi, err := div(339, 108)
if err != nil {
return 0, err
}
return approxPi * radius * radius, nil
}
But I noticed something weird. When I name a class Error
, I can subclass it like normal but when I use is
to check inheritance, then it behaves differently. I checked to make sure there are no built in classes called Error
, I can’t think of any reason why it would conflict…
class Error:
pass
class NoSaveError extends Error:
pass
class Exception:
pass
class NoSaveException extends Exception:
pass
static func test():
var err = NoSaveError.new()
print("Is sub?: ", err is NoSaveError)
print("Is super?: ", err is Error)
var ex = NoSaveException.new()
print("Is sub?: ", ex is NoSaveException)
print("Is super?: ", ex is Exception)
prints
Is sub?: true
Is super?: false
Is sub?: true
Is super?: true
I’m sorry if I’m just missing something very obvious here! I really love Godot, it is just this one little thing that is confusing to me… hopefully some of you know :3