我对手动抛出异常时 Android 中的异常如何工作感兴趣。 我尝试制作一个应用程序,您可以按一个按钮,然后会弹出一个随机异常。 在这里我注意到了一些奇怪的事情。例如,当我抛出 ArrayIndexOutOfBoundsException 时,我会得到 IlligalStateException。
产生异常的函数:
public void GenerateRandomException(View view)
{
Random rand = new Random();
int random = rand.nextInt(5);
switch(random)
{
case 0:
throw new ArrayIndexOutOfBoundsException("An ArrayIndexOutOfBoundsException occured!");
case 1:
throw new RuntimeException("A RuntimeException occured!");
case 2:
throw new NullPointerException("An NullPointerException occured!");
case 3:
throw new IllegalThreadStateException("An IllegalThreadStateException occured!");
case 4:
throw new IllegalArgumentException("An IllegalArgumentException occured!");
default:
break;
}
}
堆栈跟踪:
FATAL EXCEPTION: main
java.lang.IllegalStateException: Could not execute method of the activity
at android.view.View$1.onClick(View.java:3838)
at android.view.View.performClick(View.java:4475)
at android.view.View$PerformClick.run(View.java:18786)
at android.os.Handler.handleCallback(Handler.java:730)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:176)
at android.app.ActivityThread.main(ActivityThread.java:5419)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1046)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:862)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at android.view.View$1.onClick(View.java:3833)
... 11 more
Caused by: java.lang.ArrayIndexOutOfBoundsException: An ArrayIndexOutOfBoundsException occured!
at gamebugtracker.lib.MainActivity.GenerateRandomException(MainActivity.java:78)
... 14 more
如堆栈跟踪中所示,它表示存在由 ArrayIndexOutOfBoundsException 引起的 IlligalStateEception。
我觉得这很奇怪,ArrayIndexOutOfBoundsException 不应该是最重要的异常吗?
还是我破坏了自己的代码?
最佳答案
如您所见,您的 ArrayIndexOutOfBounds
是堆栈跟踪中最底层的“由”异常引起的。
中间还有其他 catch
block ,它们捕获您的异常并使用 Exception(String,Throwable)
将其包装到另一个异常。构造函数。在本例中,此包装器代码位于 code that transforms your XML onClick
declaration to a OnClickListener
中。 ,中间的 InitationTargetException
来自 Java 反射。
最终,异常会被顶级异常处理程序捕获,并将其记录为“致命异常”并终止您的应用程序。日志输出还包括所有嵌套异常。
关于java - Android Java 异常 - 手动抛出时它们如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23586398/