•  周一 - 周六 8.00 - 18.00
  •  苏州国际科技园(www.sispark.com.cn)
  •  0512-62651942
苏州市风云软件职业培训学校
风云动态
职业动态 您现在的位置:首页>>风云动态>> 职业动态

Java 出现错误了该如何避免?

发表时间:2017-10-19 10:56:14  浏览次数:73

1.“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;
}


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

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

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”错误,可以做这两件事:

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

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


3.“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

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


4.“(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};


5.“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

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


6.“StringIndexOutOfBoundsException”

当代码尝试访问不在字符串范围内的字符串的一部分时,就会发生这种问题。

通常,这发生在代码尝试创建字符串的子字符串,且长度与参数设置不符之时。

例子:

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


7.“NullPointerException”

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

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

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

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


8.“NoClassDefFoundError”

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

如果你编译此程序:

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)

发生这种情况的原因有:

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

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


9.“NoSuchMethodFoundError”

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

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

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


10.“NoSuchProviderException”

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

javax.mail.NoSuchProviderException

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

  • JRE配置。

  • 配置中设置的Java home。

  • 使用哪个Java环境。

  • 安全提供程序条目。


11. AccessControlException

AccessControlException表示所请求访问的系统资源,如文件系统或网络是被拒绝的。

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")


12.“ArrayStoreException”

当Java数组中转换元素的规则被破坏时,就会发生“ArrayStoreException”异常。

对于放到数组中的内容一定要非常小心。

例如,这个例子说明此程序:

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

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


13.“Bad Magic Number”

此Java软件错误消息意味着网络上的类定义文件可能出错了。

示例:

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


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

  • 数据流可能已损坏。

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


   学IT 首选苏州风云教育

风云教育-苏州园区国企,专注java软件开发培训、软件测试培训、VR/AR人才培训、企业人才定制培养的高端IT教育软件培训机构选择风云教育,不止高薪更是高起点!


      了解更多请咨询:0512-69172205

      微信咨询:wxm1519541769

      QQ咨询:1519541769

      网址:www.fy1010.com