Exceções Try-Catch em Java

O Java Try Catch é explicado aqui para atender melhor às necessidades educacionais dos alunos.

Exceções Java  Try-Catch 

Existem diferentes tipos de erros que podem ocorrer durante a execução do código Java .

Esses erros incluem erros de codificação cometidos pelo programador, erros causados ​​por entradas incorretas ou outros eventos imprevisíveis.

O programa Java geralmente falha quando ocorre um erro e gera uma mensagem de erro. É técnico dizer que o Java lançará uma exceção (lançará um erro) quando se trata de Java Try Catch .



Java Tentar & Pegar

Enquanto Java Try Catch está em execução, a instrução try permite que você teste um bloco de código em busca de erros.

Se ocorrer um erro na instrução try , a instrução catch ainda permitirá que você execute um bloco de código.

Você encontrará as palavras-chave try and catch em pares:

Sintaxe

try {
        //  The code in this block is executed
        }
        catch(Exception e) {
        // This block is used to control the errors of the code
        }

Aqui está um exemplo:

Isso resultará em um erro, pois o Java Try Catch não possui um even_Number[7].

Example: 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class Main {
public static void main(String[] args) {
int even_Numbers []={2,4,6,8};
System.out.println(even_Numbers[7]);
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Como resultado, você verá algo assim:

Exceção no encadeamento “principal” java.lang.ArrayIndexOutOfBoundsException: Índice 7 fora dos limites para comprimento 4

em Main.main(Main.java:7)

Try-catch pode ser usado para detectar erros e executar algum código para lidar com eles:

Example: 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class Main {
public static void main(String[] args) {
try {
int even_Numbers[] = {2, 4, 6, 8};
System.out.println(even_Numbers[7]);
}
catch (Exception e){
System.out.println("The Array does not have an index number upto 7");
}
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Saída:

O Array não tem um número de índice até 7

Da mesma forma, uma matriz pode ser percorrida até o número de elementos que contém, mas não mais do que isso:

Example: 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public class Main {
public static void main(String[] args) {
try {
String programming_language[] = {"Python","Java","C programming","C# Programming"};
for(int ample=0;ample<=10;ample++){
System.out.println(programming_language[ample]);
}
}
catch (Exception e){
System.out.println("The loop can not continue till 10 as the array (programming_languages) contains only 4 values");
}
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Com o Java Try Catch, você pode executar o código após a execução por meio da condição try e catch, independentemente do resultado, com a instrução final:

Example: 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class Main {
public static void main(String[] args) {
try {
float student_heights[] = {5.1f,6.2f,5.3f,6.8f,6.1f};
for(int mrx=0;mrx<=10;mrx++){
System.out.println(student_heights[mrx]);
}
}
catch (Exception e){
System.out.println("The loop can not continue till 10 as the array (programming_languages) contains only 4 values");
}
finally {
System.out.println("The Code until the error was shown will be shown by the output after going through the try and catch block");
}
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

O resultado será o seguinte:

5,1
6,2
5,3
6,8
6,1

O loop não pode continuar até 10, pois a matriz (programming_languages) contém apenas 4 valores.

O Código até que o erro fosse mostrado será mostrado pela saída após passar pelo bloco try and catch:

Example: 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public class Main {
public static void main(String[] args) {
try {
char characters[] = {'A','B','C','D','E'};
System.out.println(characters[8]);
}
catch (Exception e){
System.out.println("There is no value at index 8 of the above array");
}
finally {
System.out.println("After passing through the try and catch block the following block will execute the rest of the code");
}
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

A seguir será o resultado:

Não há valor no índice 8 da matriz acima

Depois de passar pelo bloco try and catch, o bloco seguinte executará o restante do código.


A palavra-chave de arremesso

A instrução throw permite criar um erro customizado para Java Try Catch .

As instruções de lançamento são implementadas junto com os tipos de exceção. As exceções em Java incluem ArithmeticException, FileNotFoundException, ArrayIndexOutOfBoundsException e SecurityException e etc:

Ele lançará uma exceção se a altura estiver abaixo de 4,10 pés como (“Você é um anão”). Quando a altura for 4,11 ou superior, será impresso “Você tem uma altura alta”:

Example: 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class Main {
static void check_Height(double height) {
if (height <= 4.10) {
throw new ArithmeticException("You are a DWARF ");
}
else {
System.out.println("You have a tall height");
}
}
public static void main(String[] args) {
check_Height(4.07d);
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Resultados, serão os seguintes:

Exceção no thread “main” java.lang.ArithmeticException: Você é um DWARF
em Main.check_Height(Main.java:4)
em Main.main(Main.java:12)

Você não obteria uma exceção se a altura de entrada fosse maior ou igual a 4,11:

Example: 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class Main {
static void check_Height(double height) {
if (height <= 4.10) {
throw new ArithmeticException("You are a DWARF ");
}
else {
System.out.println("You have a tall height");
}
}
public static void main(String[] args) {
check_Height(4.17d);
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Resultado será:

Você tem uma altura alta

Correspondentemente, um método odd_number pode ser usado para determinar se o inteiro de entrada é ímpar ou não. Se o inteiro fornecido for par, ele lançará uma exceção conforme mostrado abaixo:

Example: 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class Main {
static void check_Even(int odd_number) {
if (odd_number%2==0) {
throw new ArithmeticException(odd_number+" is an Even number");
}
else {
System.out.println(odd_number+" is an Odd number");
}
}
public static void main(String[] args) {
check_Even(6);
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Como demos a entrada como 6, portanto, ela lançará uma exceção:

Exceção no thread “main” java.lang.ArithmeticException: 6 é um número Par
em Main.check_Even(Main.java:4)
em Main.main(Main.java:12)

Da mesma forma, se colocarmos o valor inteiro como 17:

Example: 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class Main {
static void check_Even(int odd_number) {
if (odd_number%2==0) {
throw new ArithmeticException(odd_number+" is an Even number");
}
else {
System.out.println(odd_number+" is an Odd number");
}
}
public static void main(String[] args) {
check_Even(17);
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

 

Nós valorizamos o seu feedback.
+1
0
+1
0
+1
0
+1
0
+1
0
+1
0
+1
0

Assine a nossa newsletter
Digite seu e-mail para receber um resumo semanal de nossos melhores posts. Saber mais!
ícone