[英]Catching thrown exceptions with an Exception class I created
在GraphicsFileNotFoundException.java
我所有的都是FileNotFoundException
的導入和擴展FileNotFoundException
GraphicsFileNotFoundException
類。
在我的主java文件中,我試圖用圖形文件讀取getGraphicsFile
方法,該方法拋出GraphicsFileNotFoundException
。
經過40分鍾的努力,我的大腦陷入困境,試圖找出如何捕獲這個異常。 我已經嘗試使用try-catch塊並捕獲GraphicsFileNotFoundException
但我仍然得到錯誤
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 :/");
}
您需要正確擴展FileNotFoundException
類或手動在try
塊中引發異常。
假設這是一個賦值(我不確定為什么你還需要專門擴展這個異常),你需要再看一下你的GraphicsFileNotFoundException
類,並確保它做了它需要的東西。
要拋出異常,只需編寫條件和throw
語句:
if(needToThrow) {
throw new GraphicsFileNotFoundException();
}
要捕獲異常,請使用try
塊然后緊跟catch
塊來包圍throw語句。
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,我建議使用Eclipse ,因為很多時候它會提供需要使用自動生成的try
catch
塊捕獲的環繞聲拋出語句。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.