-
Notifications
You must be signed in to change notification settings - Fork 78
Description
Description
Hi everyone!
When I worked on integrating local Java library to my Swift package, I haven't found any mention about how to handle exceptions thrown by Java code in my Swift code.
I mean I still can use something like:
// File.swift
let myJavaClass = try JavaClass<MyJavaClass>(environment: jniEnvironment)
do {
try myJavaClass.throwException()
} catch {
print(error)
}
And I might have wrapped error in a string, and compare the results, but this is not what I really wanted to do...
The throwException() can throw multiple different exceptions, which are: FirstCustomException, SecondCustomException.
Their implementation in Java very simple:
// Java file
public class FirstException extends Exception {
public FirstException(String message) {
super(message);
}
}
public class SecondException extends Exception {
public SecondException(String message) {
super(message);
}
}
Since I added both to my swift-java config file, I can see them built by Swift-Java:
// Auto-generated by Java-to-Swift wrapper generator.
import CSwiftJavaJNI
import SwiftJava
@JavaClass("org.FirstException")
open class FirstException: Exception {
@JavaMethod
@_nonoverride public convenience init(_ arg0: String, environment: JNIEnvironment? = nil)
}
// And the same for another exception as well...
So, my naive approach was to use catch let syntax:
do {
try myJavaClass.throwException()
} catch let error as FirstException {
// do something with error
} catch let error as SecondException {
// do something with error
}
And, it's built successfully, but neither of catch let blocks are triggered.
If I added generic catch block, it is the one that will be executed.
Question
So, my question is, what is the idiomatic way of handling errors in the scenarios similar to one I described.
Thank you in advance 🙂