2016-07-02 4 views
-4

をしてFileWriter例外を処理する方法がわからない、私の方法の一つは述べていますFileWriterの場合は私のコードでは

例外を修正するためにtryとcatch文をどのように記述しますか?

+2

メッセージを適切に処理します。しかし、Javaプログラマを知っているならば、たぶん 'printStackTrace'コールを入れて残りのことを忘れてしまうでしょう。 –

+0

メソッドは例外をスローしますが、try/catchブロックを使用して例外をキャッチしないとします。 – Li357

+0

例外を処理する必要があります。 [例外のキャッチと処理](https://docs.oracle.com/javase/tutorial/essential/exceptions/handling.html)を参照してください。 – copeg

答えて

0

Java開発には、あらゆる種類の例外を処理する方法が不可欠です。 それを行うには、2つの方法があります:

public void write(String text) //notice I deleted the throw 
{ 
    try{ 
     FileWriter writer = new FileWriter(path, true); 
     PrintWriter printer = new PrintWriter(writer); 
     printer.printf("%s" + "%n", text); 
     printer.close(); 
    catch(IOException ioe){ 
     //you write here code if an ioexcepion happens. You can leave it empty if you want 
    } 
} 

と...は

public void write(String text) throws IOException //See here it says throws IOException. You must then handle the exception when calling the method 
{ 
    FileWriter writer = new FileWriter(path, true); 
    PrintWriter printer = new PrintWriter(writer); 
    printer.printf("%s" + "%n", text); 
    printer.close(); 
} 

//like this: 
public static void main(String[] args) //or wherever you are calling write from 
{ 
    try{ 
      write("hello"); //this call can throw an exception which must be caught somewhere 
     }catch(IOException ioe){/*whatever*/} 
} 
あなたは、tryブロックでthis.write` `にあなたの電話を入れて、それは誤りで述べた例外をキャッチする必要があり