50个常见的 Java 错误(第二部分)

17.“Cannot Return a Value From Method Whose Result Type Is Void”

当一个void方法尝试返回值时,就会发生此Java错误,例如在以下示例中:

public static void move()
{
    System.out.println("What do you want to do?");
    Scanner scan = new Scanner(System.in);
    int userMove = scan.nextInt();
    return userMove;
}
public static void usersMove(String playerName, int gesture)
{
    int userMove = move();
    if (userMove == -1)
    {
        break;
    }

通常,这可以通过更改方法签名匹配返回语句中的类型来修正错误。在这种情况下,void的实例可以改为int:

public static int move()
{
    System.out.println("What do you want to do?");
    Scanner scan = new Scanner(System.in);
    int userMove = scan.nextInt();
    return userMove;
}

阅读关于如何修复“Cannot Return a Value From Method Whose Result Type Is Void”错误的讨论。(@StackOverflow)

18.“Non-Static Variable … Cannot Be Referenced From a Static Context”

当编译器尝试从静态方法(@javinpaul)访问非静态变量时,就会发生此错误:

public class StaticTest {
    private int count=0;
    public static void main(String args[]) throws IOException {
        count++; //compiler error: non-static variable count cannot be referenced from a static context
    }
}

要修复“Non-Static Variable … Cannot Be Referenced From a Static Context”错误,可以做这两件事:

  • 在签名中声明此变量为静态。
  • 在静态方法中写代码创建非静态对象的实例。

阅读此介绍静态和非静态变量之间区别的教程。(@sitesbay)

19.“Non-Static Method … Cannot Be Referenced From a Static Context”

此问题发生在Java代码尝试在非静态类中调用非静态方法的情况下。 例如,以下代码:

class Sample
{
   private int age;
   public void setAge(int a)
   {
      age=a;
   }
   public int getAge()
   {
      return age;
   }
   public static void main(String args[])
   {
       System.out.println("Age is:"+ getAge());
   }
}

将返回错误:

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
Cannot make a static reference to the non-static method getAge() from the type Sample

从静态方法中调用非静态方法就是声明调用非静态方法的类的实例。

阅读此关于非静态方法和静态方法之间区别的阐述

20.“(array) <X> Not Initialized”

当数组被声明但未初始化时,你将得到“(array) <X> Not Initialized”的消息。数组的长度是固定的,因此每个数组都需要以所需的长度进行初始化。

以下代码就可以接受:

AClass[] array = {object1, object2}

即:

AClass[] array = new AClass[2];
...
array[0] = object1;
array[1] = object2;

而非:

AClass[] array;
...
array = {object1, object2};

阅读此关于如何在Java软件中初始化数组的讨论。(@StackOverflow)

21.“ArrayIndexOutOfBoundsException”

这是在代码尝试访问不在值内的数组索引时发生的运行时错误消息。以下代码将触发此异常:

String[] name = {
    "tom",
    "dick",
    "harry"
};
for (int i = 0; i <= name.length; i++) {
    System.out.print(name[i] + '\n');
}

这是另一个例子(@DukeU)

int[] list = new int[5];
list[5] = 33; // illegal index, maximum index is 4

数组索引从零开始,结束于小于数组长度的那一个。通常,当定义数组索引的限制时,通过使用“<”而不是“<=”来修复。

查看此关于索引如何触发“ArrayIndexOutOfBoundsException”Java软件错误消息的例子。(@StackOverflow)

22.“StringIndexOutOfBoundsException”

当代码尝试访问不在字符串范围内的字符串的一部分时,就会发生这种问题。通常,这发生在代码尝试创建字符串的子字符串,且长度与参数设置不符之时。下面是一个例子(@javacodegeeks):

public class StringCharAtExample {
    public static void main(String[] args) {
        String str = "Java Code Geeks!";
        System.out.println("Length: " + str.length());
        //The following statement throws an exception, because
        //the request index is invalid.
        char ch = str.charAt(50);
    }
}

和数组索引一样,字符串索引从零开始。在索引字符串的时候,最后一个字符小于字符串的长度。 “StringIndexOutOfBoundsException”Java软件错误消息通常意味着索引正在尝试访问没有包含的字符。

这里有一个说明“StringIndexOutOfBoundsException”如何发生和修复的例子。(@StackOverflow)

23.“NullPointerException”

当程序尝试使用没有赋值的对象引用时,就会出现“NullPointerException”异常。(@geeksforgeeks)

// A Java program to demonstrate that invoking a method
// on null causes NullPointerException
import java.io.*;
class GFG
{
    public static void main (String[] args)
    {
        // Initializing String variable with null value
        String ptr = null;
        // Checking if ptr.equals null or works fine.
        try
        {
            // This line of code throws NullPointerException
            // because ptr is null
            if (ptr.equals("gfg"))
                System.out.print("Same");
            else
                System.out.print("Not Same");
        }
        catch(NullPointerException e)
        {
            System.out.print("NullPointerException Caught");
        }
    }
}

Java程序经常在以下情况下出现异常:

  • 语句引用一个空值的对象。
  • 尝试访问一个已定义但未分配引用的类。

这里有一个开发人员遇到“NullPointerException”以及如何处理它的讨论。(@StackOverflow)

24.“NoClassDefFoundError”

当解释器找不到包含主方法的类的文件时,将发生“NoClassDefFoundError”异常。来自DZone的示例(@DZone):

如果你编译此程序:

class A
{
  // some code
}
public class B
{
    public static void main(String[] args)
    {
        A a = new A();
    }
}

生成两个.class文件:A.class和B.class。删除A.class文件并运行B.class文件,你将得到NoClassDefFoundError的消息:

Exception in thread "main" java.lang.NoClassDefFoundError: A
at MainClass.main(MainClass.java:10)
Caused by: java.lang.ClassNotFoundException: A
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)

发生这种情况的原因有:

  • 文件不在正确的目录内。
  • 类的名称必须与文件的名称相同(不包括文件扩展名)。名称分大小写。

阅读此关于运行Java软件时为什么发生“NoClassDefFoundError”的讨论。(@StackOverflow)

25.“NoSuchMethodFoundError”

当Java软件尝试调用类的方法并且该方法不再有定义时,将发生此错误消息(@myUND):

Error: Could not find or load main class wiki.java

当声明中有错字时,通常会出现“NoSuchMethodFoundError”Java软件错误。

阅读此教程以了解如何避免“NoSuchMethodFoundError”的错误消息。(@javacodegeeks)

26.“NoSuchProviderException”

当请求的安全提供程序不可用时,会发生“NoSuchProviderException”异常(@alvinalexander):

javax.mail.NoSuchProviderException

当试图找到为什么发生“NoSuchProviderException”时,请检查:

  • JRE配置。
  • 配置中设置的Java home。
  • 使用哪个Java环境。
  • 安全提供程序条目。

阅读关于在运行Java软件时会导致“NoSuchProviderException”原因的讨论。(@StackOverflow)

27. AccessControlException

AccessControlException表示所请求访问的系统资源,如文件系统或网络是被拒绝的,如本例中的JBossDeveloper(@jbossdeveloper):

ERROR Could not register mbeans java.security.
AccessControlException: WFSM000001: Permission check failed (permission "("javax.management.MBeanPermission" "org.apache.logging.log4j.core.jmx.LoggerContextAdmin#-
[org.apache.logging.log4j2:type=51634f]" "registerMBean")" in code source "(vfs:/C:/wildfly-10.0.0.Final/standalone/deployments/mySampleSecurityApp.war/WEB-INF/lib/log4j-core-2.5.
jar )" of "null")

阅读这篇关于解决方法的讨论,以解决“AccessControlException”错误。(@github)

28.“ArrayStoreException”

当Java数组中转换元素的规则被破坏时,就会发生“ArrayStoreException”异常。对于放到数组中的内容一定要非常小心。(@Roedyg)例如,来自JavaScan.com的这个例子说明此程序(@java_scan):

/* ............... START ............... */
 public class JavaArrayStoreException {
     public static void main(String...args) {
         Object[] val = new Integer[4];
         val[0] = 5.8;
     }
 }
 /* ............... END ............... */

可以产生以下输出:

Exception in thread "main" java.lang.ArrayStoreException: java.lang.Double
at ExceptionHandling.JavaArrayStoreException.main(JavaArrayStoreException.java:7)

当数组被初始化时,我们需要声明允许进入数组的对象的种类。 每个数组元素都需要成为相同类型的对象。

阅读此关于如何解决“ArrayStoreException”的讨论。(@StackOverflow)

29.“Bad Magic Number”

此Java软件错误消息意味着网络上的类定义文件可能出错了。 以下是来自The Server Side的示例(@TSS_dotcom):

Java(TM) Plug-in: Version 1.3.1_01
Using JRE version 1.3.1_01 Java HotSpot(TM) Client VM
User home directory = C:\Documents and Settings\Ankur
Proxy Configuration: Manual Configuration
Proxy: 192.168.11.6:80
java.lang.ClassFormatError: SalesCalculatorAppletBeanInfo (Bad magic number)
at java.lang.ClassLoader.defineClass0(Native Method)
at java.lang.ClassLoader.defineClass(Unknown Source)
at java.security.SecureClassLoader.defineClass(Unknown Source)
at sun.applet.AppletClassLoader.findClass(Unknown Source)
at sun.plugin.security.PluginClassLoader.access$201(Unknown Source)
at sun.plugin.security.PluginClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at sun.plugin.security.PluginClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.applet.AppletClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.beans.Introspector.instantiate(Unknown Source)
at java.beans.Introspector.findInformant(Unknown Source)
at java.beans.Introspector.(Unknown Source)
at java.beans.Introspector.getBeanInfo(Unknown Source)
at sun.beans.ole.OleBeanInfo.(Unknown Source)
at sun.beans.ole.StubInformation.getStub(Unknown Source)
at sun.plugin.ocx.TypeLibManager$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at sun.plugin.ocx.TypeLibManager.getTypeLib(Unknown Source)
at sun.plugin.ocx.TypeLibManager.getTypeLib(Unknown Source)
at sun.plugin.ocx.ActiveXAppletViewer.statusNotification(Native Method)
at sun.plugin.ocx.ActiveXAppletViewer.notifyStatus(Unknown Source)
at sun.plugin.ocx.ActiveXAppletViewer.showAppletStatus(Unknown Source)
at sun.applet.AppletPanel.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)

“bad magic number”错误消息可能发生在以下情况下:

  • 类文件的前四个字节不是十六进制数字CAFEBABE。
  • 类文件以ASCII模式而不是以二进制模式上传。
  • Java程序在编译之前运行。

阅读此关于如何找到“bad magic number”异常原因的讨论。(@coderanch)

30.“Broken Pipe”

此错误消息是指来自文件或网络套接字的数据流已停止工作或从另一端关闭(@ExpertsExchange)。

Exception in thread "main" java.net.SocketException: Broken pipe
      at java.net.SocketOutputStream.socketWrite0(Native Method)
      at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:92)
      at java.net.SocketOutputStream.write(SocketOutputStream.java:115)
      at java.io.DataOutputStream.write

出现broken pipe的原因通常有:

  • 耗尽磁盘暂存空间。
  • RAM可能被堵塞。
  • 数据流可能已损坏。
  • 读取管道的过程可能已经关闭。

阅读此关于Java错误“broken pipe”的讨论。(@StackOverflow)

第二部分完,敬请关注第三部分的内容。

猜你喜欢

转载自blog.csdn.net/alice_tl/article/details/80685647