English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Como o programador lança exceções manualmente no Java?

O exceção é o problema ocorrido durante a execução do programa (erro de tempo de execução). Quando ocorre uma exceção, o programa termina abruptamente e o código após a linha de exceção nunca será executado.

Example

import java.util.Scanner;
public class ExceptionExample {
   public static void main(String args[]) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter first number:");
      int a = sc.nextInt();
      System.out.println("Enter second number:");
      int b = sc.nextInt();
      int c = a/b;
      System.out.println("The result is: ");+c);
   }
}

Saída do programa

Enter first number:
100

0
Exception in thread \ / by zero
at ExceptionExample.main(ExceptionExample.java:10)

lançar exceções manualmente

Você pode usarthrow A palavra-chave throw lança explicitamente exceções definidas pelo usuário ou pré-definidas.

As exceções definidas pelo usuário e as pré-definidas têm dois tipos, cada uma representada por uma classe e herdando a classe Throwable.

Para lançar explicitamente uma exceção, é necessário instanciar sua classe e usar a palavra-chave throw para lançar seu objeto.

Example

O seguinte programa Java gera NullPointerException

public class ExceptionExample {
   public static void main(String[] args) {
      System.out.println("Hello");
      NullPointerException nullPointer = new NullPointerException();
      throw nullPointer;
   }
}

Saída do programa

Hello
Exception in thread \
   at MyPackage.ExceptionExample.main(ExceptionExample.java:6)

Cada vez que for lançada uma exceção explicitamente, é necessário garantir que a linha com a palavra-chave throw seja a última do programa. Isso é porque qualquer código escrito após isso não é acessível e, se ainda houver código abaixo dessa linha, será gerado um erro de compilação.

Example

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");
   }
}

Compilation error

D:\>javac ExceptionExample.java
ExceptionExample.java:6: error: unreachable statement
   System.out.println("How are you");
   ^
1 error

User-defined exceptions

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 anywhere it is needed for an exception.

Example

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 to initialize 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 exceptionAgeDoesnotMatchExceptionthe object, and the age value is between17e24between when an exception was 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 e 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("Nome do Estudante: ")+this.name);
      System.out.println("Idade do Estudante: "+this.age);
   }
   public static void main(String args[]) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Insira o nome do Estudante: ");
      String name = sc.next();
      System.out.println("Insira a idade do Estudante deve ser 17 e 24 (inclusive 17 e 24):");
      int age = sc.nextInt();
      Student obj = new Student(name, age);
      obj.display();
   }
}

Saída do programa

Ao executar este programa, você precisa passar os valores de nome e idade pelo teclado. Se o valor da idade fornecida não estiver17e24se a idade não estiver entre, ocorrerá uma exceção, conforme mostrado a seguir-

Insira o nome do Estudante:
Krishna
Insira a idade do Estudante deve ser 17 e 24 (inclusive 17 e 24)
14
AgeDoesnotMatchException: A idade não está entre 17 e 24
Nome do Estudante: Krishna'
Idade do Estudante: 14
   at Student.<init>(Student.java:18)
   at Student.main(Student.java:39)
Você pode gostar também