4

如果我试图打印“a”的值,为什么会显示错误?为什么异常变成了错误?

class Ankit1
{
    public static void main(String args[])
    {
        float d,a;
        try
        {
            d=0;
            a=44/d;
            System.out.print("It's not gonna print: "+a); // if exception doesn't occur then it will print and it will go on to the catch block
        }
        catch (ArithmeticException e)
        {
            System.out.println("a:" + a); // why is this an error??
        }
    }
}
4

5 回答 5

6

如果您看到错误

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
    The local variable a may not have been initialized

    at your.package.Ankit1.main(Ankit1.java:18)

其中明确指出The local variable a may not have been initialized

您收到此错误,因为您的变量a未初始化。

如果您想打印错误消息,请尝试打印...e.getMessage()p.printStackTrace()完整的堆栈跟踪。

a用这样的一些值来修复这个简单的初始化......

float a = 0;
于 2012-08-26T13:53:25.153 回答
3

"if i am trying to print value of "a" why its showing error?

Because dividing by zero throws an exception before a is initialized.

For printing the error you can print exception message or the whole stacktrace:

catch(ArithmeticException e)
{
   System.out.println(e.getMessage());
   e.printStackTrace();
}
于 2012-08-26T13:56:41.393 回答
3

a没有任何价值。由于发生了异常44/d;声明,因为可能没有价值a

Ankit1.java:14: variable a might not have been initialized
            System.out.println("Print hoga"+a);//why error come??

这是因为变量 a 未初始化。

此外,这个 44/d 语句也不会抛出任何 ArithmeticException,因为它具有浮点运算,因此没有除零异常,而是会产生无穷大。
更多请看这里

于 2012-08-26T13:54:17.653 回答
2

a未初始化
初始化默认值da

float d = 0.0f;  
float a = 0.0f;  

或使用Float代替float

Float a = null;  
于 2012-08-26T13:52:18.503 回答
1

你定义float d,a;但你没有初始化它们。如果您以后也不这样做,那么在您使用它们之前,这是一个编译时错误。
在你的try你做:
d=0;
a=44/d;

但是由于您在 a 中初始化它们try并且您在编译器内部访问它们会catch抱怨a未初始化。如果你替换为d你也会得到同样的错误。
要解决这个问题:

float d = 0,a = 0;

总是初始化你的局部变量

于 2012-08-26T14:08:29.977 回答