Hi again!
I would like to know, how to define, throw and catch custom errors. The class throwing is a "generic" class (in a framework). Current I have the following:
1. Class definition:
import Foundation
open class Examine<Element: Hashable>: NSObject, NSCopying, NSCoding {
...
override public init() {
super.init()
initialize()
}
public init(withObject object: Any!, characterSet: NSCharacterSet?) throws {
super.init()
if object is NSString {
self.initialize(withString: object as! String, characterSet: characterSet!)
}
else if object is NSArray {
self.initialize(withArray: object as! [Element])
}
else {
throw ExamineError.invalidArgument(line: #line, function: #function)
}
}
private func initialize(withString string: String, characterSet: NSCharacterSet) {
...
}
private func initialize(withArray array: [Element]!) {
...
}
....
}
2. Custom Error definiton:
public enum ExamineError: Error {
case invalidArgument(line: Int, function: String)
}
extension ExamineError: LocalizedError {
public var errorDescription: String? {
switch self {
case .invalidArgument(let line, let function):
return "Invalid argument: " + "\(line) in: " + function
}
}
public var failureReason: String? {
return "A Reason"
}
public var helpAnchor: String? {
return "Nope"
}
public var recoverySuggestion: String? {
return "try it again"
}
}
3. Test
import Foundation
import Examine
var test: Examine<Double>
do {
// the following lines should throw an error
var dbl: Double = 3.141
tes = try Examine<Double>(withObject: dbl, characterSet: NSCharacterSet.alphanumerics as NSCharacterSet)
}
catch let e as ExamineError {
print(e.localizedDescription)
}
When running this code, I get an error:
Terminated due to signal 9
Catch should "CATCH" the error and an error message should be printed. Is that right?
When trying this in playground (all definitions in playground), all works fine....
Who can help?
Best regards!