为什么不打印此例外? 为什么会出现错误?

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

class Ankit1 { public static void main(String args[]) { float d,a; try { d=0; a=44/d; System.out.print("Its not gonna printed"+a); //if Exception not occurs then it will print and it will ot goto catch block } catch(ArithmeticException e) { System.out.println("Print hoga"+a);//why error come?? } } } 

如果你看到错误

 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; 

“如果我试图打印”a“的价值,为什么它显示错误?

因为除以零会在初始化之前抛出exception。

要打印错误,您可以打印exception消息或整个堆栈跟踪:

 catch(ArithmeticException e) { System.out.println(e.getMessage()); e.printStackTrace(); } 

a没有任何价值。 exception发生在44/d ; 声明没有价值可能。

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

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

此44 / d语句也不会抛出任何ArithmeticException,因为它具有float操作,因此没有Divide-by-zero Exception而不是Infinity将是结果。
有关详情,请参阅此处

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

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

或使用Float而不是float

 Float a = null; 

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

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

float d = 0,a = 0;

始终初始化本地变量