常見的 Java 錯誤及避免方法之第五集(每集10個錯誤後續持續發佈)

41.“EOFException”

當輸入期間意外終止文件或流時,將拋出“EOFException”。 以下是拋出EOFException異常的一個示例,來自JavaBeat應用程序:

import java.io.DataInputStream;import java.io.EOFException;import java.io.File;import java.io.FileInputStream;import java.io.IOException;public class ExceptionExample {    public void testMethod1() {
        File file = new File("test.txt");
        DataInputStream dataInputStream = null;        try {
            dataInputStream = new DataInputStream(new FileInputStream(file));            while (true) {
                dataInputStream.readInt();
            }
        } catch (EOFException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {            try {                if (dataInputStream != null) {
                    dataInputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }    public static void main(String[] args) {
        ExceptionExample instance1 = new ExceptionExample();
        instance1.testMethod1();
    }
}

運行上面的程序,將拋出以下異常:

java.io.EOFExceptionat java.io.DataInputStream.readInt(DataInputStream.java:392)at logging.simple.ExceptionExample.testMethod1(ExceptionExample.java:16)at logging.simple.ExceptionExample.main(ExceptionExample.java:36)

當DataInputStream類嘗試在流中讀取數據但沒有更多數據時,將拋出“EOFException”。它也可以發生在ObjectInputStream和RandomAccessFile類中。

閱讀關於運行Java軟件時可能發生“EOFException”的討論。(@StackOverflow)

42.“UnsupportedEncodingException”

當不支持字符編碼時,會拋出此Java軟件錯誤消息(@Penn)。

public UnsupportedEncodingException()

正在使用的Java虛擬機可能不支持給定的字符集。

閱讀關於如何在運行Java軟件時處理“UnsupportedEncodingException”異常的討論。(@StackOverflow)

43.“SocketException”

“SocketException”異常表示創建或訪問套接字時出錯(@ProgramCreek)。

public void init(String contextName, ContextFactory factory) {    super.init(contextName, factory);
    String periodStr = getAttribute(PERIOD_PROPERTY);    if (periodStr != null) {        int period = 0;        try {
            period = Integer.parseInt(periodStr);
        } catch (NumberFormatException nfe) {}        if (period <= 0) {            throw new MetricsException("Invalid period: " + periodStr);
        }
        setPeriod(period);
    }
    metricsServers =
        Util.parse(getAttribute(SERVERS_PROPERTY), DEFAULT_PORT);
    unitsTable = getAttributeTable(UNITS_PROPERTY);
    slopeTable = getAttributeTable(SLOPE_PROPERTY);
    tmaxTable = getAttributeTable(TMAX_PROPERTY);
    dmaxTable = getAttributeTable(DMAX_PROPERTY);    try {
        datagramSocket = new DatagramSocket();
    } catch (SocketException se) {
        se.printStackTrace();
    }
}

當由於以下原因而達到最大連接時,通常會拋出此異常:

  • 沒有更多的網絡端口可用於應用程序。
  • 系統沒有足夠的內存來支持新的連接。

閱讀關於如何在運行Java軟件時解決“SocketException”問題的討論。(@StackOverflow)

44.“SSLException”

此Java軟件錯誤消息發生在與SSL相關的操作出現故障的時候。 以下示例來自Atlassian(@Atlassian):

com.sun.jersey.api.client.ClientHandlerException: javax.net.ssl.SSLException: java.lang.RuntimeException: Unexpected error: java.security.InvalidAlgorithmParameterException: the trustAnchors parameter must be non-empty
   at com.sun.jersey.client.apache.ApacheHttpClientHandler.handle(ApacheHttpClientHandler.java:202)
   at com.sun.jersey.api.client.Client.handle(Client.java:365)
   at com.sun.jersey.api.client.WebResource.handle(WebResource.java:556)
   at com.sun.jersey.api.client.WebResource.get(WebResource.java:178)
   at com.atlassian.plugins.client.service.product.ProductServiceClientImpl.getProductVersionsAfterVersion(ProductServiceClientImpl.java:82)
   at com.atlassian.upm.pac.PacClientImpl.getProductUpgrades(PacClientImpl.java:111)
   at com.atlassian.upm.rest.resources.ProductUpgradesResource.get(ProductUpgradesResource.java:39)
   at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
   at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
   at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
   at java.lang.reflect.Method.invoke(Unknown Source)
   at com.atlassian.plugins.rest.common.interceptor.impl.DispatchProviderHelper$ResponseOutInvoker$1.invoke(DispatchProviderHelper.java:206)
   at com.atlassian.plugins.rest.common.interceptor.impl.DispatchProviderHelper$1.intercept(DispatchProviderHelper.java:90)
   at com.atlassian.plugins.rest.common.interceptor.impl.DefaultMethodInvocation.invoke(DefaultMethodInvocation.java:61)
   at com.atlassian.plugins.rest.common.expand.interceptor.ExpandInterceptor.intercept(ExpandInterceptor.java:38)
   at com.atlassian.plugins.rest.common.interceptor.impl.DefaultMethodInvocation.invoke(DefaultMethodInvocation.java:61)
   at com.atlassian.plugins.rest.common.interceptor.impl.DispatchProviderHelper.invokeMethodWithInterceptors(DispatchProviderHelper.java:98)
   at com.atlassian.plugins.rest.common.interceptor.impl.DispatchProviderHelper.access$100(DispatchProviderHelper.java:28)
   at com.atlassian.plugins.rest.common.interceptor.impl.DispatchProviderHelper$ResponseOutInvoker._dispatch(DispatchProviderHelper.java:202)
   ...Caused by: javax.net.ssl.SSLException: java.lang.RuntimeException: Unexpected error: java.security.InvalidAlgorithmParameterException: the trustAnchors parameter must be non-empty
   ...Caused by: java.lang.RuntimeException: Unexpected error: java.security.InvalidAlgorithmParameterException: the trustAnchors parameter must be non-empty
   ...Caused by: java.security.InvalidAlgorithmParameterException: the trustAnchors parameter must be non-empty

發生這種情況的原因有:

  • 服務器或客戶端上的證書已過期。
  • 服務器端口已重置爲另一個端口。

閱讀關於可能導致Java軟件“SSLException”錯誤的討論。(@StackOverflow)

45.“MissingResourceException”

當資源丟失時,會發生“MissingResourceException”異常。如果資源在正確的類路徑中,那麼通常是因爲屬性文件沒有正確配置。下面有一個例子(@TIBCO):

java.util.MissingResourceException: Can't find bundle for base name localemsgs_en_US, locale en_US
java.util.ResourceBundle.throwMissingResourceException
java.util.ResourceBundle.getBundleImpl
java.util.ResourceBundle.getBundle
net.sf.jasperreports.engine.util.JRResourcesUtil.loadResourceBundle
net.sf.jasperreports.engine.util.JRResourcesUtil.loadResourceBundle

閱讀關於如何在運行Java軟件時修復“MissingResourceException”的討論。

46.“NoInitialContextException”

當Java應用程序想要執行命名操作但無法創建連接時,會發生“NoInitialContextException”異常(@TheASF)。

[java] Caused by: javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file:  java.naming.factory.initial[java]     at javax.naming.spi.NamingManager.getInitialContext(NamingManager.java:645)[java]     at javax.naming.InitialContext.getDefaultInitCtx(InitialContext.java:247)[java]     at javax.naming.InitialContext.getURLOrDefaultInitCtx(InitialContext.java:284)[java]     at javax.naming.InitialContext.lookup(InitialContext.java:351)[java]     at org.apache.camel.impl.JndiRegistry.lookup(JndiRegistry.java:51)

這解決起來可能會是一個複雜的問題,但這裏有一些可能導致“NoInitialContextException”Java錯誤消息的原因:

  • 應用程序可能沒有正確的憑據進行連接。
  • 代碼可能無法識別所需的JNDI實現。
  • InitialContext類可能沒有配置正確的屬性。

閱讀關於運行Java軟件時“NoInitialContextException”意味什麼的討論。(@StackOverflow)

47.“NoSuchElementException”

當迭代(例如“for”循環)嘗試訪問下一個元素而沒有元素的時候,就會出現“NoSuchElementException”異常。

public class NoSuchElementExceptionDemo{    public static void main(String args[]) {
        Hashtable sampleMap = new Hashtable();
        Enumeration enumeration = sampleMap.elements();
        enumeration.nextElement();  //java.util.NoSuchElementExcepiton here because enumeration is empty
    }
}
Output:
Exception in thread "main" java.util.NoSuchElementException: Hashtable Enumerator
        at java.util.Hashtable$EmptyEnumerator.nextElement(Hashtable.java:1084)
        at test.ExceptionTest.main(NoSuchElementExceptionDemo.java:23)

拋出“NoSuchElementException”可能的途徑:

  • Enumeration:: nextElement()
  • NamingEnumeration::next()
  • StringTokenizer:: nextElement()
  • Iterator::next()

閱讀此關於如何在Java軟件中修復“NoSuchElementException”的教程。(@javinpaul)

48.“NoSuchFieldError”

當應用程序嘗試訪問對象中的一個字段,但指定的字段不再存在於對象中時,將拋出此Java軟件錯誤消息(@sourceforge)。

public NoSuchFieldError()

通常,該錯誤在編譯器中被捕獲,但是如果在編譯和運行之間更改了類定義,則在運行時將被捕獲。

閱讀此關於如何在運行Java軟件時發現什麼導致“NoSuchFieldError”的討論。(@StackOverflow)

49.“NumberFormatException”

當應用程序嘗試將字符串轉換爲數字類型,但該數字不是有效的數字字符串時,會出現此Java軟件錯誤消息(@alvinalexander)。

package com.devdaily.javasamples;public class ConvertStringToNumber {    public static void main(String[] args) {        try {
            String s = "FOOBAR";            int i = Integer.parseInt(s);            // this line of code will never be reached
            System.out.println("int value = " + i);
        }        catch (NumberFormatException nfe) {
            nfe.printStackTrace();
        }
    }
}

可能拋出“NumberFormatException”的原因有:

  • 數字中的前導或尾隨空格。
  • 標誌不在數字前面。
  • 數字有逗號。
  • 本地化可能不會將其分類爲有效數字。
  • 數字太大,不適合數字類型。

閱讀關於如何在運行Java軟件時避免“NumberFormatException”的討論。(@StackOverflow)。

50.“TimeoutException”

當阻塞操作超時時,會出現此Java軟件錯誤消息。

private void queueObject(ComplexDataObject obj) throws TimeoutException, InterruptedException {    if (!queue.offer(obj, 10, TimeUnit.SECONDS)) {
        TimeoutException ex = new TimeoutException("Timed out waiting for parsed elements to be processed. Aborting.");        throw ex;
    }
}

閱讀此關於如何在運行Java軟件時處理“TimeoutException”的討論。(@StackOverflow)。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章