-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMain.java
More file actions
93 lines (77 loc) · 3.13 KB
/
Copy pathMain.java
File metadata and controls
93 lines (77 loc) · 3.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
package main;
import java.util.Scanner;
//https://javarush.ru/groups/posts/isklyucheniya-java
//https://javarush.ru/groups/posts/1944-iskljuchenija-checked-unchecked-i-svoi-sobstvennihe
public class Main {
public static void main(String[] args) {
// firstExample();
// secondExample();
// thirdExample();
// fourthExample();
System.out.println(fiveExample());
}
//Продемонстрировать получение ArithmeticException
public static void firstExample() {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
System.out.println(toDivide(100, n));
}
private static Integer toDivide(int a, int b) {
return a / b;
}
//throws – используется в сигнатуре методов для предупреждения, о том что метод может выбросить исключение.
//Когда вы не планируете обрабатывать исключение в своем методе,
// но хотите предупредить пользователей метода о возможных исключительных ситуациях — используйте ключевое слово throws.
// Это ключевое слово в сигнатуре метода означает, что при определенных условиях метод, может выбросить исключение.
private static Integer toDivideWithException(int a, int b) throws MyArithmeticException {
try {
return a / b;
} catch (ArithmeticException e) {
throw new MyArithmeticException(e.getMessage());
}
}
public static void secondExample() {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
try {
System.out.println(toDivide(100, n));
} catch (ArithmeticException e) {
throw new MyArithmeticException(e.getMessage());
}
}
//Продемонстрировать работу finally
public static void thirdExample() {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
try {
System.out.println(toDivide(100, n));
} catch (ArithmeticException e) {
throw new MyArithmeticException(e.getMessage());
} finally {
System.out.println("finally");
}
}
//Продемонстрировать возможность передачи своего текста
public static void fourthExample() {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
try {
System.out.println(toDivideWithException(100, n));
} catch (ArithmeticException e) {
throw new MyArithmeticException("Текст исключения");
} finally {
System.out.println("finally");
}
}
//Если оператор return содержится и в блоке catch и в finally, какой из них “главнее”?
//Вернется из блока finally.
public static String fiveExample() {
try {
return "SomeString";
} catch(Exception ex) {
return "Catch message";
} finally {
return "Finally message";
}
}
}