簡體   English   中英

Java,父類,帶有異常拋出的方法

[英]Java, parent class, method with an exception throw

我有一個方法,如何引發異常。 而不是試圖抓住。

它是一種基本的void方法,可讀取文件,

public void method(String filename){
//does some stuff to the file here
}

簡單為:

public void method(String filename) throws Exception
{
    if (error)
        throw new Exception("uh oh!");
}

或者,如果您要自定義例外:

class MyException extends Exception
{
    public MyException(String reason)
    {
        super(reason);
    }
}

public void method(String filename) throws MyException
{
    if (error)
        throw new MyException("uh oh!");
}

第一步,我認為您需要經歷java異常

這取決於您要拋出哪種異常

如果要拋出未經檢查的異常

public void method(String filename){
    if(error condition){
        throw new RuntimeException(""); //Or any subclass of RuntimeException
    }
}

如果要拋出檢查異常

public void method(String filename) throws Exception{ //Here you can mention the exact type of Exception thrown like IOExcption, FileNotFoundException or a CustomException
    if(error condition){
        throw new Exception(""); //Or any subclass of Exception - Subclasses of RuntimeException
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM