2015-10-19 78 views
0

我的java程序讀取文件或網站,並在控制檯上顯示其內容。我正在使用嵌套的try catch塊。是否有另一種方法來做到這一點,而不使用嵌套異常。什麼可以是java中嵌套異常的替代方案?

public static void main(String[] args) throws IOException 
{ 
    try 
    { 
     // Reads from file 
    } 
    catch(FileNotFoundException fnf) 
    { 
     try 
     { 
      // Assuming the entered path is to a website, Reads from a webiste, 
     } 
     catch(MalFormedURLException urlEx) 
     { 

     } 
     catch(IOException f) 
     { 

     } 
    } 
    catch(IOException e) 
    { 

    } 
} 

回答

1

改變你的邏輯。

public static void main(String[] args) throws IOException 
{ 

    try 
    { 
     if(isUrl(args)){ 
      // Reads from website 

     }else{ 
      // Reads from file 
     } 
    } 
    catch(MalFormedURLException urlEx) 
    { 

    } 
    catch(IOException f) 
    { 


    } 
} 

isUrl功能檢查,如果arg是URL通過檢查HTTP://或https://前綴或任何協議你支持。我沒有提供代碼,但你自己編碼應該相當簡單。

+0

java中沒有「isURL(String)」這樣的函數。它的JavaScript,我猜。 –

+0

我提到它是一個自定義編碼功能,你可以使用正則表達式來匹配http(s)://並且如果它存在,它的url –

+0

對不起!我誤解了你的答案......雖然好主意! –

相關問題