使用我创建的Exception类捕获抛出的异常

时间:2015-10-01 04:54:17

标签: java exception try-catch throw

GraphicsFileNotFoundException.java我所拥有的是FileNotFoundException的导入和GraphicsFileNotFoundException扩展FileNotFoundException的类getGraphicsFile

在我的主要java文件中,我尝试使用抛出GraphicsFileNotFoundException的方法GraphicsFileNotFoundException来读取图形文件。

我的大脑经过了40分钟的努力,试图找出如何捕获这个异常。我尝试使用try-catch块并捕获unreported exception GraphicsFileNotFoundException ; must be caught or declared to be thrown. public void getGraphicsFile(String fileName) throws GraphicsFileNotFoundException { String graphics = ""; Scanner getGraphics = null; try { getGraphics = new Scanner(new File(fileName)); } catch (GraphicsFileNotFoundException e){ System.out.println("Error! File can't be found :/"); } ,但我仍然收到错误

public override void ItemAdding(SPItemEventProperties properties)
{
        base.ItemAdding(properties);
        try
        {
            WriteLog("Process started", System.Diagnostics.EventLogEntryType.SuccessAudit );

            // Get Properties
            string name = properties.ListItem["Title"].ToString();
            string description = properties.ListItem["Description"].ToString();
            DateTime startDate = (DateTime)properties.ListItem["Start Date"];
            DateTime endDate = (DateTime)properties.ListItem["End Date"];

            // Create sub site
            SPWeb web = properties.OpenSite().AllWebs.Add(name.Replace(" ", string.Empty), name,
                description, 0, SPWebTemplate.WebTemplateSTS, false, false);
            web.Update();

            WriteLog("Process Completed", System.Diagnostics.EventLogEntryType.SuccessAudit);
        }
        catch (Exception ex)
        {
            WriteLog("Error:" + ex.Message + "  StackTrace --" + ex.StackTrace, System.Diagnostics.EventLogEntryType.Error);
        }
    }

1 个答案:

答案 0 :(得分:3)

您需要正确扩展FileNotFoundException类或在try块中手动抛出异常。

假设这是一个作业(我不确定为什么你需要专门扩展这个例外)你需要再看一下你的GraphicsFileNotFoundException类,并确保它做了什么它需要。

要抛出异常,只需编写条件和throw语句:

if(needToThrow) {
    throw new GraphicsFileNotFoundException();
}

要捕获异常,请使用try块围绕throw语句,然后紧跟catch块。

try {
    // code here
    if(needToThrow) {
        throw new GraphicsFileNotFoundException();
    }
}
catch(GraphicsFileNotFoundException e) {
    // handle the error (print stack trace or error message for example)
    e.printStackTrace(); // this is printing the stack trace
}

我建议您使用Eclipse,因为很多时候它会提供环绕投掷语句,需要使用自动生成的try catch块进行捕获。