Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling errors in swift with try/catch

I come from a .NET background, where error handling can be as simple as wrapping a set of statements in a try-catch. For example:

try
{
   statement1
   statement2
}
catch (ex)
{
   log(ex.Message)
}

I'm trying to add error handling in my Swift project, and all the articles I have read so far seem to indicate that error handling requires more work in Swift. In the example above, it seems I would need to know exactly which statement throws an error, and then add a "try" before it. Is it not possible to simply wrap a block of code in a try-catch, and inspect the error that gets thrown?

like image 676
Prabhu Avatar asked Jul 17 '26 14:07

Prabhu


1 Answers

Nope, you can't just wrap a block of code with try-catch.

First of all, cause not every line of code could produce exceptions. Only functions marked as "throws" could produce exceptions.

For example, you have some function:

deserialise(json: JSON) -> MyObjectType throws

And let this functions throws exceptions of type MyErrorType

That's how you should use it:

....
do {
  let deserialisedObject = try deserialise(jsonObject)
  ... // do whatever you want with deserialised object here
} catch let error as MyErrorType {
  ... // do whatever you want with error here
}
...

So, as you see, exceptions in swift is not the same thing as exceptions in C++(or other regular language) for .NET

like image 54
Simbos Avatar answered Jul 19 '26 06:07

Simbos