I am trying to use Swift 2.0 try-catch.
I originally had the following code
override func viewDidLoad()
{
var obj : Object?;
Hi( obj );
}
But it procdues an error
func Hi( open : Open? ) -> Open?
{
open!.Hi(); <-- here is error point. Fatal error !
print( "OK" );
return open;
}
Therefore I changed the code in viewDidLoad() to:
override func viewDidLoad()
{
try
{
var obj : Object?;
Hi( obj );
}
catch
{
print( "bug !!!" ); <- I want to this !!!
}
}
But it does not work !!!
I guess swift's try-catch is different than in C, C#.
How can I catch the fatal error ?
Might the following be a proper swift way?
func Hi( open : Open? ) -> Open?
{
if let op = open
{
op.Hi();
print( "OK" );
return open;
}
else
{
return nil;
}
}
There are four ways to handle errors in Swift. You can propagate the error from a function to the code that calls that function, handle the error using a do - catch statement, handle the error as an optional value, or assert that the error will not occur.
Fatal Error The fatalError() method terminates your app unconditionally. It should only be used for errors that put an app in such a corrupted state that it cannot proceed, so that the termination is the only reasonable action.
A non-fatal error is a failure in your application that didn't result in a crash for the user. In other words: the loss is recoverable, and the application can continue.
You are not supposed to catch fatalerror. It indicates a programming error. You don't catch programming errors, you fix your code. The crash is intentional and it is intentional that you cannot stop it.
Something involving the keywords try, catch and throw is available in Swift 2, but that is nothing like C++ exceptions that you seem to be thinking about.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With