• Post Reply Bookmark Topic Watch Topic
  • New Topic

Giving error : ex might not be initialized  RSS feed

 
Hitesh Kumar C
Ranch Hand
Posts: 35
Eclipse IDE Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

Code Snippet :





In the above program, when i'm calling a method printStackTrace() of Exception class in catch block, its running fine.
While, in the other code i've done the same work, created the Exception Class object and calling its printStackTrace(). But, here it is giving me the syntax error that variable ex is not initialized.

I've not initialized the variable ex in the first code as well. Does this automatically initialized by JVM in case for catch block or what???

Any suggestions please.


 
John Jai
Rancher
Posts: 1776
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If an Exception occurs in the code within the try block, then an Exception object is created which is caught in the catch block. In the case you tried you are not creating any Exception object, but only a reference.
 
Claudiu Chelemen
Ranch Hand
Posts: 75
Eclipse IDE Java Oracle
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Also, regarding your second snippet, do not think neccessarily in terms of exceptions, but in terms of Objects:

e.g.

The compiler gives the same message regardless of the object's type.

Cheers,
Claudiu
 
Campbell Ritchie
Marshal
Posts: 56570
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As John Jai has hinted, you can’t get your hands on the Exception until you are inside the catch(...) block. Even then, there might be no Exception thrown.
 
Chetan Sarnad
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can create an object of the exception and then call the printStackTrace. You can also create user defined exceptions by extending the exception class, create the instance of your user defined excepion class and throw it.
 
Randall Twede
Ranch Hand
Posts: 4696
8
Java Scala
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
just an aside. you can also get that same message in other situations.for example
String string;
if(someCondition)
{
string = "hello";
}
else
{
}
System.out.println(string);//compiler will complain
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!