2

I am able to call MessageDigest as a local variable in main() method of my code, but whenever I try creating a field variable of MessageDigest in a class, and try initializing it in a constructor, it throws a NoSuchAlgorithm exception.

My gut feeling is that we just cannot instantiate MessageDigest objects like that. Is that true?

Basically, this is what I did. I want to use this as a field variable, and not a local variable.

Qiu
  • 5,651
  • 10
  • 49
  • 56
khanna
  • 718
  • 10
  • 24

1 Answers1

1

You are correct. Because of that exception being declared to be thrown, the only way you can initialize a MessageDigest object as a member variable is via either a constructor thatbtheows that exception, or a constructor or an initializer that contains an appropriate try/catch block. Otherwise it won't compile.

user207421
  • 305,947
  • 44
  • 307
  • 483
  • Well, Very close to how I figured out, it actually was indeed throwing the exception, which needed to be caught. – khanna Aug 18 '15 at 09:05