简体   繁体   English

如何使android onCreate抛出异常

[英]How to make android onCreate throw exceptions

I am using Jackson on android to parse a JSON file into an object, and the object mapper (or object mapper.readvalue, I am not sure) throws an IOException . 我在android上使用Jackson来将JSON文件解析为对象,并且对象映射器(或对象mapper.readvalue,我不确定)抛出IOException

So I added throws IOException to my method. 所以我加了抛出IOException异常到我的方法。

public TextBox JsonToTextBox () throws IOException {
}

My problem is that I am calling that method from onCreate , which doesn't let me throw an exceptions. 我的问题是我从onCreate调用了该方法,但不允许我抛出异常。 Any ideas? 有任何想法吗?

Image which explains why I cant throw exceptions 该图说明了为什么我不能抛出异常

I know, I can use a try catch, I was just looking how to do it by throwing an exception from onCreate, thanks for the answers though 我知道,我可以使用try catch,我只是想通过从onCreate引发异常来寻找解决方法,尽管感谢您的回答

If you cannot handle the exception properly, you can "convert" it into a RuntimeException and re-throw: 如果无法正确处理该异常,则可以将其“转换”为RuntimeException并重新抛出:

@Override
protected void onCreate(Bundle savedInstanceState) {
    //...
    try {
        TextBox textBox = JsonToTextBox();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
} 

Otherwise you can catch the exception when using your method with a try catch block. 否则,将您的方法与try catch块一起使用时,您可以捕获异常。

@Override
protected void onCreate(Bundle savedInstanceState) {
    //...
    try {
        TextBox textBox = JsonToTextBox();
    } catch (IOException) {
        //Handle exception
    }
} 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM