2014-06-05 42 views
-1

如何在此遞歸中嘗試並捕獲異常?如何在遞歸中查找異常

這是代碼:

try 
    { 
    public static long faktoral(long a) 
    { 
     return a*faktoral(a-1); 
    } 
    } 
    catch(exception e){ 
      System.out.print(e.message()); 
    public static void main(String [] args) 
    { 
     System.out.print(faktoral(3)); 
    } 
+0

歡迎。請在您提問時提供有關您所犯錯誤的詳細信息。實際異常文本的追溯通常對試圖回答您的問題的人有用...... – Sheena

回答

0

您所遇到的問題是,你是超越您的最大遞歸深度,對不對?

遞歸functinon需要有逃避的一些方法....

有一些僞代碼:

function faktoral(a): 
    if a<0: 
     raise Exception ("negative") 
    if a<=1: 
     return 1 
    return a*faktoral(a-1) 

如果你覺得你當前的代碼做什麼,一行行,你會看到爲什麼我添加了額外的if語句。

如果我叫faktoral(2)你的代碼的功能將嘗試返回:

2*faktoral(1) which is: 
2*1*faktoral(0) which is: 
2*1*0*factoral(-1) 
etc 

更正後的代碼將返回:

2*faktoral(1) which is: 
2*1 
2