English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Las excepciones son problemas que ocurren durante la ejecución del programa (errores en tiempo de ejecución). Cuando se produce una excepción, el programa se detiene repentinamente y el código que sigue a la línea de la excepción nunca se ejecutará.
import java.util.Scanner; public class ExceptionExample { public static void main(String args[]) { Scanner sc = new Scanner(System.in); System.out.println("Ingrese el primer número:"); int a = sc.nextInt(); System.out.println("Ingrese el segundo número:"); int b = sc.nextInt(); int c = a/b; System.out.println("El resultado es: ");+c); } }
Resultados de salida
Ingrese el primer número: 100 Ingrese el segundo número: 0 Excepción en el hilo "main" java.lang.ArithmeticException: / por zero at ExceptionExample.main(ExceptionExample.java:10)
Puede usarthrow La palabra clave throw se utiliza para lanzar explícitamente excepciones definidas por el usuario o predefinidas.
Las excepciones definidas por el usuario y las predefinidas tienen dos tipos, cada una representada por una clase y que hereda de la clase Throwable.
Para lanzar explícitamente una excepción, debe instanciar su clase y lanzar su objeto utilizando la palabra clave throw.
El siguiente programa Java desencadena NullPointerException
public class ExceptionExample { public static void main(String[] args) { System.out.println("Hello"); NullPointerException nullPointer = new NullPointerException(); throw nullPointer; } }
Resultados de salida
Hello Excepción en el hilo "main" java.lang.NullPointerException at MyPackage.ExceptionExample.main(ExceptionExample.java:6)
Cada vez que se lance explícitamente una excepción, debe asegurarse de que la línea con la palabra clave throw sea la última línea del programa. Esto se debe a que cualquier código escrito después de esto no es accesible y si aún tiene fragmentos de código debajo de esta línea, se generará un error de compilación.
public class ExceptionExample { public static void main(String[] args) { System.out.println("Hello"); NullPointerException nullPointer = new NullPointerException(); throw nullPointer; System.out.println("How are you"); } }
D:\>javac ExceptionExample.java ExceptionExample.java:6: error: unreachable statement System.out.println("How are you"); ^ 1 error
The throw keyword is usually used to raise user-defined exceptions. Whenever we need to define our own exceptions, we need to define a class that extends the Throwable class and override the required methods.
Instantiate this class and use the throw keyword to throw it at any location where an exception is needed.
In the following Java program, we will create a custom exception class named AgeDoesnotMatchException.
public class AgeDoesnotMatchException extends Exception { AgeDoesnotMatchException(String msg) { super(msg); } }
Another class Student contains two private variables name and age, and a parameterized constructor that initializes instance variables.
As the main method, we accept the user's name and age value, and initialize the Student class by passing the accepted values.
In the constructor of the Student class, we create an exceptionAgeDoesnotMatchExceptionof an object, and the age value is between17hasta24between when an exception is triggered (using throws).
public class Student extends RuntimeException { private String name; private int age; public Student(String name, int age) { try { if (age <17|| age >24) { String msg = "Age is not between 17 y 24"; AgeDoesnotMatchException ex = new AgeDoesnotMatchException(msg); throw ex; } } catch (AgeDoesnotMatchException e) { e.printStackTrace(); } this.name = name; this.age = age; } public void display() { System.out.println("Nombre del Estudiante: ")}+this.name ); System.out.println("Edad del Estudiante: "+this.age ); } public static void main(String args[]) { Scanner sc = new Scanner(System.in); System.out.println("Ingrese el nombre del Estudiante: "); String name = sc.next(); System.out.println("Ingrese la edad del Estudiante debe ser 17 hasta 24 (incluyendo 17 y 24):"); int age = sc.nextInt(); Student obj = new Student(name, age); obj.display(); } }
Resultados de salida
Al ejecutar este programa, necesita ingresar valores de nombre y edad desde el teclado. Si el valor de edad proporcionado no está17hasta24si no está entre, se producirá una excepción, como se muestra a continuación-
Ingrese el nombre del Estudiante: Krishna Ingrese la edad del Estudiante debe ser 17 hasta 24 (incluyendo 17 y 24) 14 EdadDoesnotMatchException: La edad no está entre 17 y 24 Nombre del Estudiante: Krishna' Edad del Estudiante: 14 en Student.<init>(Student.java:18) en Student.main(Student.java:39)