简体   繁体   中英

How to write try-catch?

I have java method which encrypts a string:

public String getCurrency(String hash){
                try {
                    MessageDigest md = MessageDigest.getInstance("SHA-256");
                     md.update(hash.getBytes());

                     byte byteData[] = md.digest();

                     /** convert the byte to hex format */
                     StringBuilder sb = new StringBuilder();
                         for (int i = 0; i < byteData.length; i++) {
                     sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1));
                     }              
                    return sb.toString();
                } catch (NoSuchAlgorithmException ex) {
                    ex.printStackTrace();
                }
              return sb.toString();                
            }

I use Netheans IDE. The problem is that when I try to compile an error appears that I must create a try-catch statement for this part ("SHA-256") .

When I create it using Netbeans this code appears:

public String getCurrency(String hash){
                try {
                    MessageDigest md = MessageDigest.getInstance("SHA-256");
                     md.update(hash.getBytes());

                     byte byteData[] = md.digest();

                     /** convert the byte to hex format */
                     StringBuilder sb = new StringBuilder();
                         for (int i = 0; i < byteData.length; i++) {
                     sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1));
                     }              
                    return sb.toString();
                } catch (NoSuchAlgorithmException ex) {
                    ex.printStackTrace();
                }
              return sb.toString();                
            }

Now when I again try to compile the code this error message appears:

"varible sb is not declared"

How I can return properly the encrypted string?

As others already stated, the problem is that your sb variable is defined in the try block, hence only accessible there. Moving the declaration outside the try block will make your code compile, but I doubt it is the desired behavior.

What will happen if an exception occur when you call MessageDigest.getInstance("SHA-256") : the NoSuchAlgorithmException is catched by your catch, the stack trace is printed to the System.err and your method happily returns the toString() of an empty StringBuilder , which is the empty String . Your code which called that method is not aware of the raised exception, and can not handle the exception.

Alternatives (although what is best completely depends on your application):

  • let the method throw the exception and do proper error handling outside that method
  • catch the exception in that method as you did now, but return null instead of the empty String , which allows the caller of this method to recognize something went wrong.

A nice starting point on Exceptions is the Swing tutorial

You're declaring your StringBuilder inside the try block. This means its scope is limited to that block.

Declare it prior to the try

public String getCurrency(String hash) {
    StringBuilder sb = new StringBuilder();
    try {
        MessageDigest md = MessageDigest.getInstance("SHA-256");
        md.update(hash.getBytes());
        byte byteData[] = md.digest();

        /** convert the byte to hex format */
        for (int i = 0; i < byteData.length; i++) {
            sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1));
        }              

        return sb.toString();
    } catch (NoSuchAlgorithmException ex) {
        ex.printStackTrace();
    }
    return sb.toString();                
}

您必须在try / catch块之外声明变量sb

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM