Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is this exception is not printed? Why is it showing an error?

Tags:

java

exception

If I am trying to print the value of "a" why is it showing an error? Why has the exception become an error?

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??
        }
    }
}
like image 541
Ankit Avatar asked Dec 07 '22 12:12

Ankit


1 Answers

If you see the 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)

which clearly states The local variable a may not have been initialized

You're getting this error as your variable a wasn't initialized.

And if you want to print the error message try printing... e.getMessage() or p.printStackTrace() for complete stack trace.

To fix this simple initialize a with some value like this...

float a = 0;
like image 137
Bharat Sinha Avatar answered Mar 09 '23 00:03

Bharat Sinha