[RESOLVIDO] Exceção em Java

6 respostas
R

Boa noite pessoal.
Estou tentando fazer uma interface gráfica para uma simples calculadora que chamará métodos remotos para fazer as operações de soma e subtração usando RMI, mas estou tendo as seguintes exceções:

Janela.java:58: unreported exception java.rmi.RemoteException; must be caught or declared to be thrown
somadorActionPerformed(evt);
^
Janela.java:66: unreported exception java.rmi.RemoteException; must be caught or declared to be thrown
subtratorActionPerformed(evt);
^
Janela.java:198: unreported exception java.rmi.RemoteException; must be caught or declared to be thrown
new Janela().setVisible(true);
^
3 errors

O que estou fazendo de errado?

Aqui coloco o código da interface, espero que possam mu ajudar.
import javax.swing.JOptionPane;
import java.rmi.RemoteException;
import java.rmi.Naming;
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author robgeek
 */
public class Janela extends javax.swing.JFrame {
    /**
     * Creates new form Janela
     */
    public Janela() throws RemoteException {
        try {
            calc = (Inter_Calculadora) Naming.lookup("//192.168.1.101/CoreCalculadora");
        }  catch (RemoteException e) {
            System.out.println();
            System.out.println("RemoteException: " + e.toString());
         }  catch (Exception e) {
         System.out.println();
         System.out.println("Exception: " + e.toString());
      }
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        campo1 = new javax.swing.JTextField();
        campo2 = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        somador = new javax.swing.JButton();
        subtrator = new javax.swing.JButton();
        resposta = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Calculadora Básica");

        jLabel1.setText("Número 1");

        jLabel2.setText("Número 2");

        somador.setText("+");
        somador.setToolTipText("Somar");
        somador.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt){
                somadorActionPerformed(evt);
            }
        });

        subtrator.setText("-");
        subtrator.setToolTipText("Subtrair");
        subtrator.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt){
                subtratorActionPerformed(evt);
            }
        });

        resposta.setText("O resultado é: ");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(72, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(resposta)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(somador, javax.swing.GroupLayout.PREFERRED_SIZE, 56, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 37, Short.MAX_VALUE)
                                .addComponent(subtrator, javax.swing.GroupLayout.PREFERRED_SIZE, 52, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(campo2, javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(campo1, javax.swing.GroupLayout.Alignment.LEADING))))
                .addGap(115, 115, 115))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(65, 65, 65)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(campo1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1))
                .addGap(59, 59, 59)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(campo2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(somador)
                    .addComponent(subtrator))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 32, Short.MAX_VALUE)
                .addComponent(resposta)
                .addGap(34, 34, 34))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void somadorActionPerformed(java.awt.event.ActionEvent evt) throws RemoteException {//GEN-FIRST:event_somadorActionPerformed
        int numero1, numero2;
        try{
            numero1 = Integer.parseInt(
                this.campo1.getText());
        }catch (Exception e){
            JOptionPane.showMessageDialog(this, "Primeiro número inválido",
                    "Erro",JOptionPane.ERROR_MESSAGE);
            return;
        }
        try{
            numero2 = Integer.parseInt(
                this.campo2.getText());
        }catch (Exception e){
            JOptionPane.showMessageDialog(this, "Secundo número inválido",
                    "Erro",JOptionPane.ERROR_MESSAGE);
            return;
        }
        int resposta = this.calc.somar(numero1, numero2);
        this.resposta.setText("O resultado é: "+ resposta);
    }//GEN-LAST:event_somadorActionPerformed

    private void subtratorActionPerformed(java.awt.event.ActionEvent evt) throws RemoteException {//GEN-FIRST:event_subtratorActionPerformed
        int numero1, numero2;
        try {
            numero1 = Integer.parseInt(
                    this.campo1.getText());
        } catch (Exception e) {
            JOptionPane.showMessageDialog(this, "Primeiro número inválido",
                    "Erro", JOptionPane.ERROR_MESSAGE);
            return;
        }
        try {
            numero2 = Integer.parseInt(
                    this.campo2.getText());
        } catch (Exception e) {
            JOptionPane.showMessageDialog(this, "Secundo número inválido",
                    "Erro", JOptionPane.ERROR_MESSAGE);
            return;
        }
        int resposta = this.calc.subtrair(numero1, numero2);
        this.resposta.setText("O resultado é: " + resposta);
    }//GEN-LAST:event_subtratorActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) throws RemoteException {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Janela.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Janela.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Janela.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Janela.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new Janela().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextField campo1;
    private javax.swing.JTextField campo2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel resposta;
    private javax.swing.JButton somador;
    private javax.swing.JButton subtrator;
     private Inter_Calculadora calc; //Declarando calc.
    // End of variables declaration//GEN-END:variables
}

Obrigado.

6 Respostas

V

Boa noite meu amigo, acredito que seu erro deva estar acontecendo por conter chaves a mais ou a falta de fechamento delas.

pergunta já debugou seu projeto?

V

Boa noite meu amigo, acredito que seu erro deva estar acontecendo por conter chaves a mais ou a falta de fechamento delas.

pergunta já debugou seu projeto?

R

Não debuguei não, na verdade a interface fiz no netbeans, e as únicas coisas que acrescentei no código ali foram a declaração de “calc” lá no final do código o try catch no construtor “Janela” e os throws RemoteException nos métodos que tratam o que acontece quando os botões de soma e subtração forem apertados.

E
<blockquote>Janela.java:58: unreported exception java.rmi.RemoteException; must be caught or declared to be thrown

somadorActionPerformed(evt);

^

Janela.java:66: unreported exception java.rmi.RemoteException; must be caught or declared to be thrown

subtratorActionPerformed(evt);

^

Janela.java:198: unreported exception java.rmi.RemoteException; must be caught or declared to be thrown

new Janela().setVisible(true); </blockquote>

Na linha 58 voce está chamando o metodo somadorActionPerformed que pode lançar uma RemoteException. O mesmo na linha 66 e 198, porem com diferentes metodos.
Traduzindo a mensagem … você precisa tratar ou re-lançar as exceções …

R

Sim mas nos três métodos eu coloquei o thows RemoteException junto da implementação dos métodos.

R

Funcionou cara, foi só colocar um try catch(RemoteException e) envolvendo as chamadas dos métodos que deu certo.
Obrigado a todos que tentaram me ajudar.

Criado 6 de junho de 2012
Ultima resposta 6 de jun. de 2012
Respostas 6
Participantes 3