domingo, 20 de mayo de 2012

Excepción con throws y throw

 Excepciones chequeadas

Ejemplo 1


MyException.java

public class MyException extends Exception {

    public MyException(String msg){

       super(msg);

    }

}

Prueba.java

public class MyTest {

    static int  divide(int first,int second) throws MyException{

        if(second==0) {

            throw new MyException("No se define division por cero");

        }

        return first/second;

   }

    public static void main(String[] args){

         try {

                    System.out.println(divide(4,0));

        } catch (MyException exc) {

                    exc.printStackTrace();

        }

     }

}

Ejemplo 2


A.java


 public class A {


    String a;
 

    B [] listaB;
 

    int c = 0;

    A(String n, int max) {
 

        a = n;
 

        listaB = new Empleado [max];
 

    }

    void generarB(String a, int d ) throws {
 

       if (c < listaB.length ) {
 

            listaB[c++] = new B(a, d);

       else throw new ExceptionArray(a);

       }

    }

 }

ExceptionArray.java

public class ExceptionArray extends Exception {

     ExceptionArray(String a) {

        super("No es posible añadir el elemento " + a);

    }

    . . .

}

// Otra forma de manejar el error se da en el llamado al método.

Main.java

public class Main {

  public static void main(String[] args) {

     A myObj = new A("Hola",3);
 

       try {
 

             myObj.generarB("Primer dato", 500);
 

       } catch (ExceptionArray e) {
 

             System.out.println(e.toString());
 

             System.exit(1);
 

       }
 

   }


}

Ejemplo3



 Main.java

public class Main {

  public static int metodoA (int n) {


     if (n < 0)
 
        throw new IllegalArgumentException(n + " debe ser positivo");
 
     if (n >= 60)
 
         throw new IllegalArgumentException(n + " debe ser menor a 60");
 
     return 0;
 
  }

  public static void main(String[] args) {

        System.out.println(metodoA(90));

  }

}

 Excepciones en tiempo de ejecución

Ejemplo 4

A.java

public class A{
 
   public static void main(String args[]){ 
 
   String str = "prueba"; 
 
   int suma = 0;

        for(int i = 0; i <= str.length(); i++){ 
 
              try{ 
 
                   suma += Integer.parseInt(str.charAt(i) + ""); 
 
              }catch(IndexOutOfBoundsException e){ 
 
                     System.out.print("Desbordo limite de cadena  "); 
 
              }catch(NumberFormatException e1){ 
 
                     System.out.print("No es de tipo entero "); 
 
              }finally{ 
 
                     System.out.println("i= " + i); 
 
              } 
 
 } 
 
 System.out.println("Suma: " + suma); 
 
 } //main 
 
} //class

No hay comentarios:

Publicar un comentario

Muchas gracias por su comentario, será revisado y pronto se publicará.