Swift: The different between try, try? and try!
In my previous story, we learn about how to handle error gracefully in swift with do
try
catch
syntax. If you want to see the most common way to handle error code, please look at my previous story, let’t focus on the difference between try
try?
and try!
in this story.
Simple way to handle error:
at the Step 3, we handle the function with any potential errors.
Then, what is do
try
and catch
? Let’s discuss it one by one.
Keyword do
— This keyword starts the block of code that contains the function that have any potential errors.
Keyword try
— with this keyword, we should use in front of the function that have any potential errors (have throws
keyword).
Keyword catch
— If the function fails at the run time, the execution will fall into this catch block.
So, what happen when we call throwable function with try
but without do
and catch
? When we do this, the compiler will show an error Errors thrown from here are not handled
.
With that errors, is it means that we always should handle throwable function with do
try
catch
? The answer is no. Fortunately, swift provide other ways to handle this.
First: Converting Errors to Optional Values
We can convert the value to an optional value. We can use try?
to handle it. If the function thrown an error when evaluation try?
expression, the value of the result is nil
. The we should handle optional value as usual.
Second: Disabling Error Propagation
Sometimes, we know that a throwable function will not throw an error at runtime. In this case, we can handle with try!
to disable error propagation. But, if an error actually is thrown, we will get a runtime error (app crash).
For example, still use the same function to validate url. When we hardcode the urlString with valid url, it means that we are sure that validateUrl
function will not thrown an error at the run time. So, we can handle this case with this sample code:
That’s it!
Now try to implement on your project, and if you find better way to handle error, don’t forget to share with me!
If it was useful to you then please 👏 for me. Thanks!!!