Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

swift can catch fatal error?

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;
    }
}
like image 598
AKillUea Avatar asked Jul 10 '15 07:07

AKillUea


People also ask

How does Swift handle fatal errors?

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.

What is fatal error in Swift?

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.

What is non fatal error in Swift?

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.


1 Answers

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.

like image 89
gnasher729 Avatar answered Oct 01 '22 13:10

gnasher729