2012-03-15 11 views
5
public class ThrowException { 
    public static void main(String[] args) { 
     try { 
      foo(); 
     } 
     catch(Exception e) { 
      if (e instanceof IOException) { 
       System.out.println("Completed!"); 
      } 
      } 
    } 
    static void foo() { 
     // what should I write here to get an exception? 
    } 
} 

Ciao! Ho appena iniziato a imparare le eccezioni e ho bisogno di ottenere un expetion, quindi per favore qualcuno può fornirmi una soluzione? Sarei molto grato. Grazie!come lanciare un IOException?

+0

Qual è 'foo' e come si relaziona a' a'? –

+1

Questa è solo la sintassi Java di base che qualsiasi libro o introduzione a Java ti insegnerà. Suggerisco di leggerne un po '. – ColinD

risposta

15
static void foo() throws IOException { 
    throw new IOException("your message"); 
} 
+0

dovrei scrivere questo nel metodo foo? –

+0

Sì. Se questa linea viene raggiunta, verrà generata un'eccezione. –

+1

nota che il metodo foo deve essere dichiarato per generare l'eccezione. altrimenti si otterrà un errore del compilatore – ewok

6
try { 
     throw new IOException(); 
    } catch(IOException e) { 
     System.out.println("Completed!"); 
    } 
1
throw new IOException("Test"); 
1

Ho appena iniziato eccezioni l'apprendimento e la necessità di catturare un'eccezione

un'eccezione

throw new IOException("Something happened") 

Per catturare questa eccezione è meglio non utilizzare Exception bec ause è molto generica, invece, intercettare l'eccezione specifica che si sa come gestire:

try { 
    //code that can generate exception... 
}catch(IOException io) { 
    // I know how to handle this... 
} 
1

Se l'obiettivo è quello di gettare l'eccezione dal metodo foo(), è necessario dichiararla come segue:

public void foo() throws IOException{ 
    \\do stuff 
    throw new IOException("message"); 
} 

Poi, nel tuo principale:

public static void main(String[] args){ 
    try{ 
     foo(); 
    } catch (IOException e){ 
     System.out.println("Completed!"); 
    } 
} 

si noti che, a meno che foo è dichiarato per lanciare un'IOException, il tentativo di prendere uno si tradurrà in un errore di compilazione. Codificandolo con uno catch (Exception e) e uno instanceof si impedisce l'errore del compilatore, ma non è necessario.

0

Forse questo aiuta ...

Annotare il modo più pulito per catturare eccezioni nell'esempio qui sotto - non è necessario il e instanceof IOException.

public static void foo() throws IOException { 
    // some code here, when something goes wrong, you might do: 
    throw new IOException("error message"); 
} 

public static void main(String[] args) { 
    try { 
     foo(); 
    } catch (IOException e) { 
     System.out.println(e.getMessage()); 
    } 
} 
1

Si prega di provare il seguente codice:

throw new IOException("Message");