有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java UnsupportedEncodingException错误,但我没有读取任何文件?

我正在做一个构建区块链的任务,我有一个叫做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

共 (1) 个答案

  1. # 1 楼答案

    这意味着你必须包围你的Sha1。使用try/catch块调用hash(),该块捕获UnsupportedEncodingException,或将其添加到throws子句中

    在Java中,有检查和未检查的异常。未经检查的异常会在运行时抛出,而不会事先发出警告。检查异常是api或函数的一种方式,用于警告您可能会发生异常,并且您应该在编译时处理它。你的例外情况就是这样

    要查看有关Java中异常的更多信息,请参阅https://docs.oracle.com/javase/tutorial/essential/exceptions/

    您还可以在此处找到有关选中/未选中异常的解释:https://www.geeksforgeeks.org/checked-vs-unchecked-exceptions-in-java/