如果我试图打印"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??
}
}
}
Run Code Online (Sandbox Code Playgroud)
如果你看到错误
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)
Run Code Online (Sandbox Code Playgroud)
这清楚地说明了 The local variable a may not have been initialized
由于您的变量a未初始化,因此收到此错误.
如果要打印错误消息,请尝试打印... e.getMessage()或p.printStackTrace()完整的堆栈跟踪.
要修复这个简单的初始化a,有这样的值......
float a = 0;
Run Code Online (Sandbox Code Playgroud)