Is there a way in Dart to mark a function as throwing an exception?
Asked Answered
J

1

23

I was trying to find a way in Flutter/Dart to mark a function that may throw an exception during its execution. After some time searching in the documentation and Google I did not find any way of doing this.

In other language, for example Swift, Java, Kotlin, etc I know we have such mechanism. Sample code in Swift is:

func doSomething() throws { ... }

Does anyone know if this exists in Dart? I think it will be useful.

If it does not exist due to Dart language desing then maybe anyone can explain the reason behind this decision.

Thanks in advance!

Jaal answered 13/2, 2020 at 12:36 Comment(0)
A
14

There is no way in Dart to mark a function as potentially throwing.

All functions should be assumed to potentially throw (if for no other reason, then because of an out-of-memory or stack-overflow situation).

If you look at Swift, the throws is about exceptions, not errors. Dart does not distinguish the two, you can throw anything. Swift has put itself in a place between Java ("have to declare all thrown exceptions") and Dart or C# ("Can't declare exceptions").

Marking a function as "throwing" doesn't help the compiler in any way because it has to assume that all other functions might too. The Swift approach is there to ensure that distinctively marked exceptions are not ignored. Unless you want to, then you can try! them and turn the exception into an error.

If a function does throw as part of normal usage, you should document it in the function's documentation.

Dart also have the issue of function types. Is a function from int to int the same type as another function from int to int if the latter can throw? Separating function types into throwing and non-throwing get complicated quickly. Even more so if you want to specify what it throws. It's not impossible, but it's one more complication.

The one thing that you will get with the Dart null safety update (currently being worked on), is a way to state that a function always throws. If you make the return type Never in null-safe code, then the type system will prevent you from returning any value, and since a function call must end by either returning a value or throwing, a call to a function with return type Never can only end by throwing.

Aorta answered 13/2, 2020 at 15:17 Comment(2)
Meteor can smash you at any moment also. That doesn't mean that we should not place safety belt in a car. I found this topic by trying to know if File.writeAsBytes() can throw an error or not. In my case it was easier to just look at source code and see what it does. But if you don't have access to sources and code is not well documented you can get a lot of crashes for no good reason. Personally, I like swift way to handle this issue more.Jameyjami
Very funny but sensible commentEmpurple

© 2022 - 2024 — McMap. All rights reserved.