首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >常见的 Java 错误及避免方法之第四集(每集10个错误后续持续发布)

常见的 Java 错误及避免方法之第四集(每集10个错误后续持续发布)

作者头像
用户1289394
发布2018-11-08 14:51:31
1.3K0
发布2018-11-08 14:51:31
举报
文章被收录于专栏:Java学习网Java学习网

31.“Could Not Create Java Virtual Machine”

当我们尝试调用带有错误参数的Java代码时,通常会产生此Java错误消息(@ghacksnews):

Error: Could not create the Java Virtual MachineError: A fatal exception has occurred. Program will exit.

这通常是由于代码中的声明存在错误或为其分配适当的内存而引起的。

阅读关于如何修复Java软件错误“Could Not Create Java Virtual Machine”的讨论。(@StackOverflow)

32.“class file contains wrong class”

当Java代码尝试在错误的目录中寻找类文件时,就会出现“class file contains wrong class”的问题,导致类似于以下内容的错误消息:

MyTest.java:10: cannot access MyStruct 
bad class file: D:\Java\test\MyStruct.java file does not contain class MyStruct Please remove or make sure it appears in the correct subdirectory of the classpath. 
MyStruct ms = new MyStruct();

要修复此错误,以下这些提示可以提供帮助:

  • 确保源文件的名称和类的名称匹配——包括大小写。
  • 检查软件包语句是否正确或是否缺失。
  • 确保源文件位于正确的目录中。

阅读此关于如何修复“class file contains wrong class”错误的讨论。(@StackOverflow)

33.“ClassCastException”

“ClassCastException”消息指示了Java代码正在尝试将对象转换为错误的类。在来自Java Concept of Day的这个例子中,运行以下程序:

package com;class A{    int i = 10;
}class B extends A{    int j = 20;
}class C extends B{    int k = 30;
}public class ClassCastExceptionDemo{    public static void main(String[] args)
    {
        A a = new B();   //B type is auto up casted to A type
        B b = (B) a;     //A type is explicitly down casted to B type.
        C c = (C) b;    //Here, you will get class cast exception
        System.out.println(c.k);
    }
}

导致以下错误:

Exception in thread “main” java.lang.ClassCastException: com.B cannot be cast to com.Cat com.ClassCastExceptionDemo.main(ClassCastExceptionDemo.java:23)

Java代码将创建一个类和子类的层次结构。为了避免“ClassCastException”错误,请确保新类型属于正确的类或其父类之一。如果使用泛型,则编译代码时可能会捕获这些错误。

阅读此教程以了解如何修复“ClassCastException”的Java软件错误。(@java_concept)

34.“ClassFormatError”

“ClassFormatError”消息指示链接错误,并且发生在类文件不能被读取或解释为类文件的时候。

Caused by: java.lang.ClassFormatError: Absent Code attribute in method that is        not native or abstract in class file javax/persistence/GenerationTypeat java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClassCond(Unknown Source)
at java.lang.ClassLoader.defineClass(Unknown Source)
at java.security.SecureClassLoader.defineClass(Unknown Source)
at java.net.URLClassLoader.defineClass(Unknown Source)
at java.net.URLClassLoader.access$000(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)

有若干原因会导致“ClassFormatError”错误:

  • 类文件以ASCII模式而不是二进制模式上传。
  • Web服务器必须以二进制而不是ASCII格式发送类文件。
  • 可能会有一个类路径错误,阻止了代码找到类文件。
  • 如果类被加载两次,那么第二次将导致抛出异常。
  • 正在使用旧版本的Java运行时。

阅读此关于导致Java“ClassFormatError”错误的原因的讨论。(@StackOverflow)

35.“ClassNotFoundException”

“ClassNotFoundException”仅在运行时发生——意味着在编译期间有一个类在运行时缺失了。这是一个链接错误。

很像“NoClassDefFoundError”,在以下情况下会出现这个问题:

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

阅读此关于导致“ClassNotFoundException”原因的更多案例的讨论。(@StackOverflow)。

36.“ExceptionInInitializerError”

此Java问题发生在静态初始化出错的时候(@GitHub)。 当Java代码稍后使用该类时,将发生“NoClassDefFoundError”错误。

java.lang.ExceptionInInitializerError
  at org.eclipse.mat.hprof.HprofIndexBuilder.fill(HprofIndexBuilder.java:54)
  at org.eclipse.mat.parser.internal.SnapshotFactory.parse(SnapshotFactory.java:193)
  at org.eclipse.mat.parser.internal.SnapshotFactory.openSnapshot(SnapshotFactory.java:106)
  at com.squareup.leakcanary.HeapAnalyzer.openSnapshot(HeapAnalyzer.java:134)
  at com.squareup.leakcanary.HeapAnalyzer.checkForLeak(HeapAnalyzer.java:87)
  at com.squareup.leakcanary.internal.HeapAnalyzerService.onHandleIntent(HeapAnalyzerService.java:56)
  at android.app.IntentService$ServiceHandler.handleMessage(IntentService.java:65)
  at android.os.Handler.dispatchMessage(Handler.java:102)  at android.os.Looper.loop(Looper.java:145)  at android.os.HandlerThread.run(HandlerThread.java:61)
Caused by: java.lang.NullPointerException: in == null
  at java.util.Properties.load(Properties.java:246)  at org.eclipse.mat.util.MessageUtil.(MessageUtil.java:28)  at org.eclipse.mat.util.MessageUtil.(MessageUtil.java:13)
  ... 10 more

修复此错误我们需要更多的信息。在代码中使用getCause()可以返回导致错误的异常。

阅读此关于如何追踪ExceptionInInitializerError原因的讨论。(@StackOverflow)

37.“IllegalBlockSizeException”

当长度消息不是8字节的倍数时,那么在解密期间就会抛出“IllegalBlockSizeException”异常。以下是一个出自ProgramCreek.com的示例(@ProgramCreek):

@Overrideprotected byte[] engineWrap(Key key) throws IllegalBlockSizeException, InvalidKeyException {    try {        byte[] encoded = key.getEncoded();        return engineDoFinal(encoded, 0, encoded.length);
    } catch (BadPaddingException e) {
        IllegalBlockSizeException newE = new IllegalBlockSizeException();
        newE.initCause(e);        throw newE;
    }
}

“IllegalBlockSizeException”可能是由以下原因引起的:

  • 使用不同的加密和解密算法选项。
  • 要解密的消息可能在传输中被截断或乱码。

阅读关于如何防止IllegalBlockSizeException Java软件错误消息的讨论。(@StackOverflow)

38.“BadPaddingException”

当使用填充来创建一个消息而不是8字节的倍数时,那么在解密期间可能会出现“BadPaddingException”异常。这是出自Stack Overflow的一个例子(@StackOverflow):

javax.crypto.BadPaddingException: Given final block not properly paddedat com.sun.crypto.provider.SunJCE_f.b(DashoA13*..)at com.sun.crypto.provider.SunJCE_f.b(DashoA13*..)at com.sun.crypto.provider.AESCipher.engineDoFinal(DashoA13*..)at javax.crypto.Cipher.doFinal(DashoA13*..)

加密数据是二进制的,所以不要尝试将其存储在字符串或在加密期间没有被正确填充的数据中。

阅读关于如何防止BadPaddingException的讨论。(@StackOverflow)

39.“IncompatibleClassChangeError”

“IncompatibleClassChangeError”是LinkageError的一种形式,如果一个在基类在编译子类之后发生变化,那么就会出现此异常。下面这个例子来自于How to Do in Java(@HowToDoInJava):

Exception in thread "main" java.lang.IncompatibleClassChangeError: Implementing classat java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(Unknown Source)
at java.security.SecureClassLoader.defineClass(Unknown Source)
at java.net.URLClassLoader.defineClass(Unknown Source)
at java.net.URLClassLoader.access$000(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClassInternal(Unknown Source)
at net.sf.cglib.core.DebuggingClassWriter.toByteArray(DebuggingClassWriter.java:73)
at net.sf.cglib.core.DefaultGeneratorStrategy.generate(DefaultGeneratorStrategy.java:26)
at net.sf.cglib.core.AbstractClassGenerator.create(AbstractClassGenerator.java:216)
at net.sf.cglib.core.KeyFactory$Generator.create(KeyFactory.java:144)
at net.sf.cglib.core.KeyFactory.create(KeyFactory.java:116)
at net.sf.cglib.core.KeyFactory.create(KeyFactory.java:108)
at net.sf.cglib.core.KeyFactory.create(KeyFactory.java:104)
at net.sf.cglib.proxy.Enhancer.(Enhancer.java:69)

出现“IncompatibleClassChangeError”有可能的原因是:

  • 忘记了主方法的静态。
  • 非法使用了legal类。
  • 类被改变了,并且存在通过旧的签名从另一个类到这个类的引用。尝试删除所有类文件并重新编译所有内容。

尝试解决“IncompatibleClassChangeError”的这些步骤(@javacodegeeks)

40.“FileNotFoundException”

当具有指定路径名的文件不存在时,将抛出此Java软件错误消息。

@Override public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {    if (uri.toString().startsWith(FILE_PROVIDER_PREFIX)) {        int m = ParcelFileDescriptor.MODE_READ_ONLY;        if (mode.equalsIgnoreCase("rw")) m = ParcelFileDescriptor.MODE_READ_WRITE;
        File f = new File(uri.getPath());
        ParcelFileDescriptor pfd = ParcelFileDescriptor.open(f, m);        return pfd;
    } else {        throw new FileNotFoundException("Unsupported uri: " + uri.toString());
    }
}

除了没有指定路径名的文件之外,这可能意味着现有文件无法访问。

阅读关于为什么会抛出“FileNotFoundException”的讨论。(@StackOverflow)

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2018-10-20,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 Java学习网 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 31.“Could Not Create Java Virtual Machine”
  • 32.“class file contains wrong class”
  • 33.“ClassCastException”
  • 34.“ClassFormatError”
  • 35.“ClassNotFoundException”
  • 36.“ExceptionInInitializerError”
  • 37.“IllegalBlockSizeException”
  • 38.“BadPaddingException”
  • 39.“IncompatibleClassChangeError”
  • 40.“FileNotFoundException”
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档