首页 > 解决方案 > 为什么 try-catch 块无法处理 IllegalAccessException?

问题描述

我试图在调用者方法中捕获 IllegalAccessException。但它无法抓住它。相反,它给出了一个错误。

{
    static void fun()
    {
      try{
        System.out.println("Inside fun(). ");
        throw new IllegalAccessException("demo");
      }catch(IllegalAccessException e){
            throw e;
      }
    }
    public static void main(String args[])
    {
        try
        {
            fun();
        }
        catch(IllegalAccessException e)
        {
            System.out.println("caught in main.");
        }
    }
}

标签: javaexceptionillegalaccessexception

解决方案


您需要添加throws IllegalAccessException方法签名,因为 IllegalAccessException 是已检查的预期,需要在签名中进行标记。您是否会使用不需要在签名中添加的 RuntimeExpection。


推荐阅读