package com.codemonkey;
import static java.lang.System.out;
import static java.lang.System.err;
public class TestExcepciones{
public static void main(String ... args){
out.println("\t---- Excepciones en Java ----\n");
//java.lang.Object
//java.lang.Throwable
//java.lang.Exception
//java.lang.RuntimeException
//java.lang.ArithmeticException
//División x cero
try{
int division = 4/0;
}catch(ArithmeticException | NumberFormatException ae){
err.println("Division por cero: ArithmeticException");
}catch(Exception ex){
ex.printStackTrace();
}//Salida: Division por cero: ArithmeticException
//java.lang.Object
//java.lang.Throwable
//java.lang.Exception
//java.lang.RuntimeException
//java.lang.IllegalArgumentException
//java.lang.NumberFormatException
//Numero con formato no valido
try{
Integer entero = Integer.parseInt("123G");
}catch(NumberFormatException | ArithmeticException nfe){
err.println("Numero con formato no valido: NumberFormatException");
}catch(Exception ex){
ex.printStackTrace();
}//Salida: Numero con formato no valido: NumberFormatException
//java.lang.Object
//java.lang.Throwable
//java.lang.Exception
//java.lang.RuntimeException
//java.lang.ClassCastException
//Casteo no valido
try{
Animal animal = new Perro();
Perro perro = (Perro) animal;
Gato gato = (Gato) animal;
}catch(ClassCastException | NullPointerException cce){
err.println("Casteo no valido: ClassCastException");
}catch(Exception ex){
ex.printStackTrace();
}//Salida:Casteo no valido: ClassCastException"
//java.lang.Object
//java.lang.Throwable
//java.lang.Exception
//java.lang.RuntimeException
//java.lang.IndexOutOfBoundsException
//java.lang.ArrayIndexOutOfBoundsException
//Acceder a un indice que no existe
CharSequence[] charSequence = {"Adelaida","Arenita"};
try{
charSequence[2] = "El guero";
}catch(ArrayIndexOutOfBoundsException | NullPointerException aie){
err.println("Tratas de acceder a un indice que no existe: ArrayIndexOutOfBoundsException");
}catch(Exception ex){
ex.printStackTrace();
}//Salida: Tratas de acceder a un indice que no existe: ArrayIndexOutOfBoundsException
//java.lang.Object
//java.lang.Throwable
//java.lang.Exception
//java.lang.RuntimeException
//java.lang.NullPointerException
//Tratar de hacer uso de un objeto null
String cadena = null;
try{
cadena = cadena.toUpperCase();
}catch(NullPointerException npe){
err.println("Objeto null: NullPointerException");
}catch(Exception ex){
ex.printStackTrace();
}
//Salida: Objeto null: NullPointerException
}
}
Excepciones más comunes en Java
Be the first to comment
You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.