Swift Can Catch Fatal Error

Catching an error from a non-throwing method

You can use the init(exactly:) constructor, it will not throw an error but it will return nil if the value is to large

guard let value = Int(exactly: pow(Double(1000000000), Double(10))) else {
//error handling
}

How can you mark a method that it is fatal, like `fatalError`?

As pointed out by others, the issue was something on my machine specifically. The following (returning 'Never') works as expected.

func myFatalError() -> Never {
print("Doing something fatal")
}

Why the swift throws exception despite try?

try? does not catch exceptions. It catches thrown errors. Those are different things in Swift. Exceptions are at the Objective-C level and cannot be caught by Swift at all (they can't be safely caught in ObjC in most cases either, but that's a different discussion).

The solution in this case is to use JSONEncoder rather than JSONSerialization. JSONEncoder is a pure-Swift system. JSONSerialization is bridged from ObjC.

let body = try? JSONEncoder().encode([data])

See Handling Errors for more information:

Error handling in Swift resembles exception handling in other languages, with the use of the try, catch and throw keywords. Unlike exception handling in many languages—including Objective-C—error handling in Swift does not involve unwinding the call stack, a process that can be computationally expensive. As such, the performance characteristics of a throw statement are comparable to those of a return statement.

If you want to use JSONSerialization, it's important to recognize that it is a programming error to call it this way. The exception is intended to crash the program (even in ObjC). The correct way to write this code is:

if JSONSerialization.isValidJSONObject([data]), // <=== first, check it is valid
let body = try? JSONSerialization.data(withJSONObject: [data]) {
print("success")
} else {
print("unable to make body for call")
}

See the docs for more information:

If obj will not produce valid JSON, an exception is thrown. This exception is thrown prior to parsing and represents a programming error, not an internal error. You should check whether the input will produce valid JSON before calling this method by using isValidJSONObject(_:).

The thrown error from JSONSerialization is only to indicate an internal error in the serializer, not an attempt to encode an invalid object:

error

If an internal error occurs, upon return contains an NSError object with code NSPropertyListWriteInvalidError that describes the problem.

How to fix that error “Fatal Error in ContentView.swift”?

The reason for this failing is either the url for "start.txt" is nil or try? String(contentsOf: startWordsURL) fails. In order to help you debug and become an understanding why your current code design is bad consider this design:

func startGame() {
// 1.find the URL for start.txt in our app bundle
guard let startWordsURL = Bundle.main.url(forResource: "start",withExtension: "txt") else{
//assign the default value
rootWord = "yamori"
// if the url is not found this will print in the console
print("File could not be found")
return
}

do{
// 2.load start.txt into a string
let startWords = try String(contentsOf: startWordsURL)
// 3.split the string up into an array of strings, splitting on line breaks
let allWords = startWords.components(separatedBy: "\n")
// 4.pick one random word, or use "yamori" as a sensible default
rootWord = allWords.randomElement() ?? "yamori"
} catch{
//if the file couldn´t be read this will print the error in the console
print(error)
}
}


Related Topics



Leave a reply



Submit