Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I'm getting error: NoSuchAlgorithmException; must be caught or declared to be thrown?

Tags:

java

My code:

import java.io.*;
import java.util.*;
import java.math.*;
import java.security.*;
import java.nio.charset.*;
public class Solution {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String s = sc.nextLine();
        MessageDigest md = MessageDigest.getInstance("SHA-256");
        byte[] hashBytes = md.digest(s.getBytes(StandardCharsets.UTF_8));
        StringBuilder sb = new StringBuilder();
        for(byte b : hashBytes){
            sb.append(String.format("%02x",b));
        }
        System.out.println(sb.toString());
    }
}

I'm trying to print the SHA-256 encryption value of a string but while compiling this error is showing:

error: unreported exception NoSuchAlgorithmException; must be caught or declared to be thrown
        MessageDigest md = MessageDigest.getInstance("SHA-256");
                                                    ^
like image 812
Ajax Avatar asked Jan 20 '26 22:01

Ajax


1 Answers

You need to have it surrounded by try-catches

    MessageDigest md = null;
    try {
            md = MessageDigest.getInstance("SHA-256");
    }catch(NoSuchAlgorithmException e) {
            System.out.println("Something is wrong");
    }
like image 113
Soner Say Avatar answered Jan 22 '26 11:01

Soner Say



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!