Ir ao conteúdo
  • Cadastre-se

Error: unreported exception exception; must be caught or declared to be thrown


Posts recomendados

Bom dia.

 

Estou tendo certas dificuldade em realizar a criptografia de meu arquivo.

 

Pesquisei na internet e em alguns outros foruns e estavam dizendo que necessitava estar dentro de um bloco try catch para funcionar. porém mesmo realizando este metodo da o seguinte erro: error: unreported exception Exception; must be caught or declared to be thrown.

 

Segue o meu codigo:

import java.io.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.lang.IllegalStateException;
import java.util.NoSuchElementException;
import java.util.Scanner;
public class CryptoDummy
{
   private static byte[] textoCifrado;
   private static byte[] textoDecifrado;
   static String sMsgClara;
  static String sMsgCifrada = null;
  static String sMsgDecifrada = null;
   static byte[] bMsgClara = null;
  static byte[] bMsgCifrada = null;
   static byte[] bMsgDecifrada = null;
   
   public CryptoDummy()
   {
      textoCifrado = null;
      textoDecifrado = null;
      sMsgClara = pegaTexto();
   }
   public static void geraChave(File fDummy) throws IOException
   {
   // Gera uma chave Dummy simetrica (dk: 0 a 100):
      int dk = (int) (Math.random()*101);
   // Grava a chave Dummy simetrica em formato serializado
      ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(fDummy));
      oos.writeObject(dk);
      oos.close();
   }
   public static void geraCifra(byte[] texto, File fDummy)
   throws IOException, ClassNotFoundException
   {
      ObjectInputStream ois = new ObjectInputStream (new FileInputStream (fDummy));
      int iDummy = (Integer) ois.readObject();
      ois.close();
      textoCifrado = texto;
      for(int i = 0; i < texto.length; i++)
      {
         textoCifrado = (byte) (textoCifrado + i + iDummy);
      }
   }
   public static byte[] getTextoCifrado() throws Exception
   {
      return textoCifrado;
   }
   public void geraDecifra(byte[] texto, File fDummy)
   throws IOException, ClassNotFoundException
   {
      ObjectInputStream ois = new ObjectInputStream (new FileInputStream (fDummy));
      int iDummy = (Integer) ois.readObject();
      ois.close();
      textoDecifrado = texto;
      for(int i = 0; i < texto.length; i++)
      {
         textoDecifrado = (byte) (textoDecifrado - i - iDummy);
      }
   }
   public byte[] getTextoDecifrado() throws Exception
   {
      return textoDecifrado;
   }
   
   
   public static void criptografa() throws Exception
   {
      try{
      // Instancia um objeto da classe CryptoDummy
      //CryptoDummy cdummy = new CryptoDummy();
      // Gera a chave criptografica Dummy simetrica e nome do arquivo onde sera armazenada
         geraChave(new File ("login.txt"));
      // Gera a cifra Dummy da mensagem dada, com a chave Dummy simetrica dada
         geraCifra(bMsgClara, new File ("chave.dummy"));
      // Recebe o texto cifrado
         bMsgCifrada = getTextoCifrado();
      // Converte o texto byte[] no equivalente String
         sMsgCifrada = (new String (bMsgCifrada, "ISO-8859-1"));
      }
      catch ( NoSuchElementException elementException )
      {
         System.err.println( "File improperly formed." );
         System.exit( 1 );
      } // end catch
      catch ( IllegalStateException stateException )
      {
         System.err.println( "Error reading from file." );
         System.exit( 1 );
      } // end catch
   }
 
   
   public void descriptografa() throws Exception
   {
      try
      {
      // Gera a decifra Dummy da mensagem dada, segundo a chave Dummy simetrica gerada
         geraDecifra(bMsgCifrada, new File ("chave.dummy"));
      // recebe o texto decifrado
         bMsgDecifrada = getTextoDecifrado();
      // Converte o texto byte[] no equivalente String
         sMsgDecifrada = (new String (bMsgDecifrada, "ISO-8859-1"));
      }
      catch ( NoSuchElementException elementException )
      {
         System.err.println( "File improperly formed." );
         System.exit( 1 );
      } // end catch
      catch ( IllegalStateException stateException )
      {
         System.err.println( "Error reading from file." );
         System.exit( 1 );
      } // end catch
   }
   
    public String pegaTexto()
   {
      String line = "";
      Scanner in = new Scanner(System.in);
      try
      {
         in = new Scanner(new File("login.txt"));
      } // end try
      catch( FileNotFoundException fileNotFoundException )
      {
         System.err.println( "Error opening file." );
         System.exit( 1 );
      } // end catch
      try
      {
         while (in.hasNext())
         {
            in.nextLine();
            
         //System.out.println(line);
         }
      }
      catch ( NoSuchElementException elementException )
      {
         System.err.println( "File improperly formed." );
         in.close();
         System.exit( 1 );
      } // end catch
      catch ( IllegalStateException stateException )
      {
         System.err.println( "Error reading from file." );
         System.exit( 1 );
      } // end catch
      //System.out.println(line);
      return line ;
   }

}

 

E quando chamo esse método em outra classe da a seguinte mensagem:

 

error: unreported exception Exception; must be caught or declared to be thrown

 

java.png

Link para o comentário
Compartilhar em outros sites

voce criou suas duas funções 'criptografa()' e 'descriptografa()' falando que elas podiam retornar um erro ('throws Exception'). Quando voce utiliza 'throws Exception', sempre que voce for chamar essa função voce deve coloca-la dentro de um try/catch.

 

Exemplo:

/*
	CERTO
*/
public void funcao() throws Exception{
	//Sua logica        
}

//Ao chamar voce deve utilizar try/catch
//....
try{
	funcao();
}catch(Exception erro){
	//Logica para lidar com o erro
}
//....

 

o que é estranho em seu código é o fato de voce ja estar lidando com erros dentro da própria função, então não vejo o motivo de retornar um erro no seu caso.  

 

Link para o comentário
Compartilhar em outros sites

Visitante
Este tópico está impedido de receber novas respostas.

Sobre o Clube do Hardware

No ar desde 1996, o Clube do Hardware é uma das maiores, mais antigas e mais respeitadas comunidades sobre tecnologia do Brasil. Leia mais

Direitos autorais

Não permitimos a cópia ou reprodução do conteúdo do nosso site, fórum, newsletters e redes sociais, mesmo citando-se a fonte. Leia mais

×
×
  • Criar novo...

 

GRÁTIS: ebook Redes Wi-Fi – 2ª Edição

EBOOK GRÁTIS!

CLIQUE AQUI E BAIXE AGORA MESMO!