Skip to content

Instantly share code, notes, and snippets.

@mcrisc
Last active September 30, 2020 13:11
Show Gist options
  • Save mcrisc/e149698e80f8d85a1f1ee7bc7a8c19b8 to your computer and use it in GitHub Desktop.
Save mcrisc/e149698e80f8d85a1f1ee7bc7a8c19b8 to your computer and use it in GitHub Desktop.
Exemplos de tratamento de exceções
import java.util.Scanner;
public class ExemploExcecao {
public static void main(String[] args) {
double[] precos = new double[] {3.95, 1.30, 2.80};
System.out.println("Cotação de Preços");
System.out.print("Fornecedor: ");
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
sc.close();
double preco = precos[i];
System.out.printf("Fornecedor %d: R$ %.2f\n", i, preco);
}
}
import java.util.Scanner;
public class ExemploExcecao2 {
public static void main(String[] args) {
double[] precos = new double[] {3.95, 1.30, 2.80};
System.out.println("Cotação de Preços");
System.out.print("Fornecedor: ");
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
sc.close();
try {
double preco = precos[i];
System.out.printf("Fornecedor %d: R$ %.2f\n", i, preco);
} catch (ArrayIndexOutOfBoundsException e) {
System.err.println("Código de fornecedor inválido!");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment