Level Up Coding

Coding tutorials and news. The developer homepage gitconnected.com && skilled.dev && levelup.dev

Follow publication

Member-only story

Three things you didn’t know about exception handling in Dart and Flutter

Artem Goncharov
Level Up Coding
Published in
13 min readMar 6, 2021

--

Photo by Ben Hershey on Unsplash

Sorry for the clickbait title of the article, I’m experimenting with different styles… But I’d like to not disappoint you and will provide all those 3 things :)

What is an exception?

There are two types of exception definition:

  1. An exception is an inability of an operation to fulfill its contract
  2. An exception is an unexpected behavior

It seems that the first definition can include the second one as the unexpected behavior can be one of the reasons why the operation couldn’t fulfill its contract. The other reasons could include more or less expected problems — like connection loss, corruption of the file, and so on.

As an example let’s consider this function:

This function returns the remaining money in our account. In order to do this, the function should hit our backend and request the account balance and this operation can fail because of various reasons — the network is down, the server is down, the contract between frontend and backend was changed, etc… All those reasons lead to an inability of our operation to fulfill its contract. However, all of those problems can be foreseen and we can add them to the contract. The only thing we can’t expect is unexpected behavior :). For instance, we anticipated all the problems except one: when backend in some cases returns text “negative” instead of the balance of our account — so this becomes unexpected for us (it’s a completely artificial example but just to give you an idea).

The more we know about our system the less chance some unexpected behavior occurs.

The next question is what we are going to do in all those exceptional cases. Do we want to react differently for each case or maybe we don’t care much if the server is down or returns some unexpected data? It’s the question of our system design but anyway we need a way to catch those exceptions separately or as a general exceptional…

--

--

Responses (1)

Write a response