50个常见的 Java 错误及避免方法(第二部分)

接上文50个常见的 Java 错误及避免方法(第一部分)

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

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

public static void move()

{

    System.out.println("Whatdo you want to do?");

    Scanner scan= new Scanner(System.in);

    int userMove = scan.nextInt();

    return userMove;

}

public static void usersMove(StringplayerName, int gesture)

{

    int userMove = move();

    if (userMove == -1)

    {

        break;

    }

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

public static int move()

{

    System.out.println("Whatdo you want to do?");

    Scanner scan= new Scanner(System.in);

    int userMove = scan.nextInt();

    return userMove;

}

18.“Non-Static Variable … Cannot Be Referenced From a Static Context”当编译器尝试从静态方法访问非静态变量时,就会发生此错误:

public class StaticTest {

    private intcount=0;

    public staticvoid main(Stringargs[]) throws IOException {

        count++;//compiler error: non-static variable count cannotbe referenced from a static context

    }

}

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

  • 在签名中声明此变量为静态。

  • 在静态方法中写代码创建非静态对象的实例。

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 staticreference 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};


21.“ArrayIndexOutOfBoundsException”

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

String[] name = {

    "tom",

    "dick",

    "harry"

};

for (int i = 0; i <= name.length; i++) {

    System.out.print(name[i] + '\n');

}

int[] list = new int[5];

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

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

22.“StringIndexOutOfBoundsException”

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

public class StringCharAtExample {

    public staticvoid main(String[]args) {

        Stringstr = "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软件错误消息通常意味着索引正在尝试访问没有包含的字符。

23.“NullPointerException”

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

// A Java program to demonstrate thatinvoking a method

// on null causes NullPointerException

import java.io.*;

class GFG

{

    public staticvoid main(String[] args)

    {

        // Initializing String variable with null value

        Stringptr = 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程序经常在以下情况下出现异常:

  • 语句引用一个空值的对象。

  • 尝试访问一个已定义但未分配引用的类。

24.“NoClassDefFoundError”

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

如果你编译此程序:

class A

{

  // some code

}

public class B

{

    public staticvoid 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)

发生这种情况的原因有:

  • 文件不在正确的目录内。

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

25.“NoSuchMethodFoundError”

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

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

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

26.“NoSuchProviderException”

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

javax.mail.NoSuchProviderException

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

  • JRE配置。

  • 配置中设置的Java home。

  • 使用哪个Java环境。

  • 安全提供程序条目。

27. AccessControlException

AccessControlException表示所请求访问的系统资源,如文件系统或网络是被拒绝的,如本例中的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")" incode source "(vfs:/C:/wildfly-10.0.0.Final/standalone/deployments/mySampleSecurityApp.war/WEB-INF/lib/log4j-core-2.5.jar )" of "null")

28.“ArrayStoreException”

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

/* ............... 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)

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

29.“Bad Magic Number”

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

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:\Documentsand 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(UnknownSource)

at sun.applet.AppletClassLoader.findClass(UnknownSource)

atsun.plugin.security.PluginClassLoader.access$201(Unknown Source)

at sun.plugin.security.PluginClassLoader$1.run(UnknownSource)

at java.security.AccessController.doPrivileged(NativeMethod)

at sun.plugin.security.PluginClassLoader.findClass(UnknownSource)

at java.lang.ClassLoader.loadClass(Unknown Source)

at sun.applet.AppletClassLoader.loadClass(UnknownSource)

at java.lang.ClassLoader.loadClass(Unknown Source)

at java.beans.Introspector.instantiate(Unknown Source)

at java.beans.Introspector.findInformant(UnknownSource)

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(NativeMethod)

at sun.plugin.ocx.TypeLibManager.getTypeLib(UnknownSource)

at sun.plugin.ocx.TypeLibManager.getTypeLib(UnknownSource)

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程序在编译之前运行。

30.“Broken Pipe”

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

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可能被堵塞。

  • 数据流可能已损坏。

  • 读取管道的过程可能已经关闭。

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

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值