简体   繁体   English

如何在方法onClick(View v)中抛出例外

[英]how to throw an exeption in method onClick(View v)

First, I already reviewed some similar questions but the answers didn't help me :( 首先,我已经复习了一些类似的问题,但是答案并没有帮助我:(

I trying to program an Android application and this is my problem 我试图编写一个Android应用程序,这是我的问题

public void onClick(View v)  {
        String url = Buscar_Random();
        //do something with the variable url

I want to call the method Buscar_Random , this method throws an IOException , so I need to call this exception in the method onClick . 我想调用方法Buscar_Random ,该方法引发IOException ,因此我需要在方法onClick调用此异常。 So i tried this: 所以我尝试了这个:

public void onClick(View v) throws  IOException {

But onClick is an override method, so I receive this message: overridden method does not throw 'java.io.IOException' 但是onClick是重写方法,因此我收到此消息: overridden method does not throw 'java.io.IOException'

I also tried this: 我也试过这个:

    public void onClick(View v)  {
    try {
        String url = Buscar_Random.main();
        //do something with the variable url
    } catch (IOException e){
        e.printStackTrace();
    }

And this is the weirdest part, the app compiles but when i call the method in the app in my Android, the app closes itself (and doesn't even show me the message "Unfortunately blahblah has stopped working" 这是最奇怪的部分,该应用程序已编译,但是当我在Android的应用程序中调用该方法时,该应用程序会自行关闭(甚至不会显示“不幸的是blahblah已停止工作”的消息)

I also tried to use a RuntimeException , but neither worked :( 我也尝试使用RuntimeException ,但都没有用:(

What can I do? 我能做什么?

Thanks 谢谢

Your second example is doing it right. 第二个例子是正确的。

As for the crash, just because a method doesn't specifically declare that it throws a certain Exception doesn't mean it won't. 至于崩溃,只是因为方法没有明确声明它抛出某个Exception并不意味着就不会。 It could be throwing a NullPointerException, RemoteException, IllegalArgumentException, etc. Also, just because there's no "App has stopped" message doesn't mean the app didn't crash. 它可能会引发NullPointerException,RemoteException,IllegalArgumentException等。此外,仅因为没有“应用程序已停止”消息并不意味着该应用程序没有崩溃。 That dialog isn't always shown. 该对话框并不总是显示。

If you want to just ignore any and all errors from that method (probably a bad idea, since the current crash is probably a bug you need to fix), just catch Exception: 如果您只想忽略该方法的所有错误(可能是一个坏主意,因为当前的崩溃可能是您需要修复的错误),只需捕获Exception:

try {
    //whatever
} catch (Exception e) {}

However, you should really look at the Logcat viewer (bottom toolbar) in Android Studio. 但是,您应该真正查看Android Studio中的Logcat查看器(底部工具栏)。 Filter by your app only, and set the level to Error and find out why your app is crashing. 仅按您的应用进行过滤,并将级别设置为“错误”,以找出导致应用崩溃的原因。

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

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