Unreachable catch block for Unknownhostexception. This Exception is Never thrown from the Try statement body

Asked

Viewed 56 times

0

Speak devs, all right? I am trying to connect Mongdb to a Java application and I get this error:

Unreachable catch block for UnknownHostException. This exception is never thrown from the try statement body

They know how to fix?

Follows the code:

Connection class

package conexao;

import java.net.UnknownHostException;
import java.util.logging.Level;
import java.util.logging.Logger;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.Mongo;

public class Connection 
{
    DB BaseDados;
    DBCollection colecao;
    BasicDBObject document = new BasicDBObject();
    
    public Connection()
    {
        try
        {
            //Conectando ao servidor mongobd
            Mongo m = new Mongo("localhost", 27017);
            //Mongo m = new Mongo("localhost", 127.0.0.1);
            //Caso não funcione
            
            //Conectando a base de dados teste
            BaseDados = m.getDB("teste");
            
            colecao = BaseDados.getCollection("pessoa");
            
            System.out.println("Conexao efetuada com sucesso");
        }
        catch(UnknownHostException e)
        {
            Logger.getLogger(Connection.class.getName()).log(Level.SEVERE, null, e);
        }
    }
    
    public boolean inserir(String Dado)
    {
        document.put("RG", Dado);
        colecao.insert(document);
        return true;
    }
    
    public void mostrar()
    {
        DBCursor cursor = colecao.find();
        while(cursor.hasNext())
        {
            System.out.println(cursor.next());
        }
    }
    
    public boolean atualizar(String DadoAntigo, String DadoNovo)
    {
        document.put("RG", DadoAntigo);
        BasicDBObject DocNovo = new BasicDBObject();
        document.put("RG", DadoNovo);
        colecao.findAndModify(document,DocNovo);
        return true;
    }
    
    public boolean remover(String Dado)
    {
        document.put("RG", Dado);
        colecao.remove(document);
        return true;
    }
    
}

Main Class

package conexao;

public class Principal {

    public static void main(String[] args)
    {
        Connection conexao = new Connection();
        
        conexao.inserir("9254063");
        conexao.mostrar();

    }

}
  • Is this Unknownhostexception the same class of Ngo that throws the error? Because the message seems clear, nothing inside Try launches the Exception q vc is trying to capture, if yes try to check if everything is right with the classpath

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.