我正在做一个构建区块链的任务,我有一个叫做Block的类。在第26行,我尝试计算哈希值时出现以下错误:
错误:未捕获的异常java.io.UnsupportedEncodingException
必须被捕获或声明为抛出
我正在读取另一个类中的文件,但是在那个文件中我没有这个问题。我不确定自己在做什么错事
import java.util.Date;
import java.sql.Timestamp;
import java.io.*;
public class Block {
private int index; //index of the block in the list
public String hash; //the hash of the object
public String previousHash; //the hash of the previous object in the blockchain
private java.sql.Timestamp timeStamp; //time at which the transaction has been process
private Transaction transaction; //the transaction object
private String nonce; //the random string for proof of work
public static void main (String args[]) throws IOException {
// System.out.println(timeStamp.getTIme());
} //closes main method
//Block constructor
public Block(String data, String previousHash) {
this.previousHash = previousHash;
this.timeStamp = new Timestamp(System.currentTimeMillis());
} //closes constructor
//calculating hash
public String calculateHash() {
String calculatedHash = Sha1.hash(previousHash);
return calculatedHash;
} //closes calculateHash method
} //closes class
答案 0 :(得分:0)
这意味着您必须用一个try / catch块来包围Sha1.hash()调用,该块可以捕获UnsupportedEncodingException,或者将其添加到throws子句中。
在Java中,有检查和未检查的异常。未经检查的异常会在运行时中抛出,而不会事先发出警告。已检查的异常是api或函数的一种方式,用于警告您可能会发生异常,并且应在编译时进行处理。例外情况就是这种情况。
要查看有关Java异常的更多信息,请参阅https://docs.oracle.com/javase/tutorial/essential/exceptions/
您还可以在此处找到有关已检查/未检查异常的说明:https://www.geeksforgeeks.org/checked-vs-unchecked-exceptions-in-java/