我感兴趣的是手动播放时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,是最重要的例外吗? 还是我打破了自己的代码?
答案 0 :(得分:2)
正如您所看到的,您的ArrayIndexOutOfBounds
是最基本的"由"堆栈跟踪中的异常。
中间还有其他catch
块捕获您的异常并使用Exception(String,Throwable)
构造函数将其包装到另一个异常中。在这种情况下,此包装器代码位于code that transforms your XML onClick
declaration to a OnClickListener
中,中间InvocationTargetException
来自Java反射。
最终异常会被顶级异常处理程序捕获,该异常处理程序将其记录为" FATAL EXCEPTION"并终止您的应用程序。日志输出也包括所有嵌套异常。