2013-11-22 43 views
0

我正在尝试学习Java异常处理。我写了下面的代码:了解Java异常处理:简单尝试捕获块

import java.util.*; 
public class Problem1 
{ 
    static Scanner length = new Scanner(System.in); 
    public static void main(String[] args) 
    { 
      double x; 
      double y; 

      System.out.println("Input a length in Feet and than Inches."); 

      x = length.nextDouble(); 
      y = length.nextDouble(); 

      try 
      { 
        System.out.println("Feet - Inches:" + x * 12); 
        System.out.println("Inches - Centimeters:" + y * 2.14); 
      } 

      catch (InputMismatchException imeRef) 
      { 
        System.out.println("Do not use letters" + imeRef.toString()); 
      } 
    } 
} 

该程序只是将英尺和英寸输入转换为英寸。我试图通过给它一个输入来打破它:

-1 
e 

该程序中断,但我没有正确捕捉和处理异常。任何想法我做错了什么?

感谢

+0

您希望在将用户输入转换为double时捕获任何异常。这发生在以下代码行中: 'x = length.nextDouble();' 'y = length.nextDouble();' 因此这两行应该已经在try语句中 – Ashish

+0

是的!我一直盯着这个这么久,错过了显而易见的。谢谢! – MrGuerino

+0

如果评论有用,请投票选举。谢谢 – Ashish

回答

2

您需要将其读取用户输入到try块2点输入的语句。只有在读取输入并处理catch中的错误时,才会抛出错误,这些语句需要位于try块中,因为catch只处理在其对应的try块中抛出的异常。

try { 
    x = length.nextDouble(); // moved inside try 
    y = length.nextDouble(); // moved inside try 
    System.out.println("Feet - Inches:" + x * 12); 
    System.out.println("Inches - Centimeters:" + y * 2.14); 
} 
1

把下面的两行 -

x = length.nextDouble(); 
y = length.nextDouble(); 

try块内 -

try { 
    x = length.nextDouble(); 
    y = length.nextDouble(); 

    System.out.println("Feet - Inches:" + x * 12); 
    System.out.println("Inches - Centimeters:" + y * 2.14); 
} 
catch (InputMismatchException imeRef) { 
    System.out.println("Do not use letters" + imeRef.toString()); 
} 

一个catch块只捕获内部由报表抛出的匹配异常其相应的try块。

1

您不会发生异常是因为调用length.nextDouble()时为变量x和y引发异常。

x = length.nextDouble(); 
    y = length.nextDouble(); 

但是你不要把它们放在try - catch代码中。把上面的两行代码尝试 - 赶上,你会发现异常。

1

catch语句只捕获在其相应的try块中抛出的异常。

这就是你想要的。这会提示用户每次输入一个问题,并重新输入并重新输入。请注意catch中的length.next() - 这是避免无限循环所必需的 - 您必须超越该不良令牌。

while (true) { 
    try { 
     System.out.println("Input a length in feet"); 
     double x = length.nextDouble(); 

     System.out.println("Input a length in inches"); 
     double y = length.nextDouble(); 

     System.out.println("Feet - Inches:" + x * 12); 
     System.out.println("Inches - Centimeters:" + y * 2.14); 

     break; 
    } 

    catch (InputMismatchException imeRef) { 
     System.out.println("Do not use letters" + imeRef.toString()); 

     // need to purge the bad token 
     length.next(); 
    } 
}