java - 为什么不打印此异常?为什么显示错误?

标签 java exception

如果我尝试打印“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??
        }
    }
}

最佳答案

如果你看到错误

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)

这清楚地说明了 局部变量 a 可能尚未初始化

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

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

要修复这个简单的初始化 a 的一些值,像这样...

float a = 0;

关于java - 为什么不打印此异常?为什么显示错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12130659/

相关文章:

java - 如何在后台任务 javaFX 中捕获的异常中显示对话框中的错误消息?

c# - 使线程将异常传播到上层线程

Java Socket问题,缓冲区同时接收两个数据包。

.net - 使用 WCF netNamedPipeBinding 时找不到命名管道

java - 从类中读取字节

java - 当屏幕关闭时,Android 服务似乎会暂停

exception - hudson |加载作业时出现 NullPointerException

android - 解析 json 时避免很多 try-catch 博客

java - 有没有一种好方法来跟踪传递给类的参数变量

java - 使用 javascript 提交按钮登录网站(使用 Java)