2012-03-15 23 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? 
    } 
} 

Merhaba! Sadece istisnaları öğrenmeye başladım ve bir spora yakalanma ihtiyacım var, bu yüzden lütfen bana bir çözüm sunabilir mi? Çok minnettar olurum. Teşekkürler!Bir IOException nasıl atılır?

+0

'foo' nedir ve nasıl a'' ile ilgisi nedir? –

+1

Bu, Java'ya yazılacak herhangi bir kitabın veya tanıtımın size öğreteceği basit Java sözdizimi. Biraz okumayı öneriyorum. – ColinD

cevap

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

bunu foo yönteminde yazmalı mıyım? –

+0

Evet. Bu satıra ulaşılırsa, bir istisna atılır. –

+1

, istisnayı atmak için foo yönteminin bildirilmesi gerektiğini unutmayın. aksi halde bir derleyici hatası alacaksınız – ewok

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

Sadece istisnalar öğrenmeye başladı ve

bu istisna iyidir değil yakalamak için bir istisna

throw new IOException("Something happened") 

atmak için bir istisna yakalamak gerekir Exception bec kullanın Amaç foo() yönteminden istisna ise

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

, aşağıdaki gibi beyan etmek gerekir:: ause çok jenerik, bunun yerine, nasıl işleneceğini biliyor belirli istisna yakalamak için

Sonra ana içinde
public void foo() throws IOException{ 
    \\do stuff 
    throw new IOException("message"); 
} 

:

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

Not yani foo biri derleyici hata ile sonuçlanır yakalamaya çalışan, bir IOException atmak bildirilmediği sürece. Bir catch (Exception e) ve instanceof kullanarak kodlamak, derleyici hatasını engeller, ancak gereksizdir.

0

Belki bu

Not temizleyici yolu aşağıdaki örnekte durumları yakalamak ... yardımcı olur - Eğer e instanceof IOException gerekmez.

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

Aşağıdaki kodu deneyin:

throw new IOException("Message"); 
İlgili konular