You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
In the previous section we saw that we said that the `main()` function could throw an `InterruptedException`. This section is all about handling exceptions such as that!
1162
+
1163
+
**General Exception Handling with `try catch`**
1164
+
1165
+
```java
1166
+
publicclassMain {
1167
+
publicstaticvoidmain(String[ ] args) {
1168
+
try {
1169
+
int[] myNumbers = {1, 2, 3};
1170
+
System.out.println(myNumbers[10]);
1171
+
} catch (Exception e) {
1172
+
System.out.println("Something went wrong.");
1173
+
}
1174
+
}
1175
+
}
1176
+
```
1177
+
1178
+
You can also use `finally` to run things at the end even if an exception was caught!
1179
+
1180
+
```java
1181
+
publicclassMain {
1182
+
publicstaticvoidmain(String[] args) {
1183
+
try {
1184
+
int[] myNumbers = {1, 2, 3};
1185
+
System.out.println(myNumbers[10]);
1186
+
} catch (Exception e) {
1187
+
System.out.println("Something went wrong.");
1188
+
} finally {
1189
+
System.out.println("The 'try catch' is finished.");
1190
+
}
1191
+
}
1192
+
}
1193
+
```
1194
+
1195
+
**Throw and Throws**
1196
+
1197
+
Use `throw` to throw an exception.
1198
+
1199
+
```java
1200
+
thrownewArithmeticException("/ by zero");
1201
+
```
1202
+
1203
+
Use `throws` to indicate that the method it is attached to **might** throw some exception. The caller to the method has the responsibility of handling the exception in a `try catch` block.
1204
+
1205
+
```java
1206
+
type method_name(parameters) throws exception_list {}
1207
+
1208
+
// exception_list is a comma separated list of all the exceptions which a method might throw.
1209
+
```
1210
+
1211
+
1212
+
1213
+
### Assertions
1214
+
1215
+
Mandate that some statement evaluates to true, otherwise, throw an assertion error.
1216
+
1217
+
This is usually used for test cases!
1218
+
1219
+
```java
1220
+
assert assertion_expression :"printed string if false"
1221
+
```
1222
+
1223
+
1224
+
1225
+
### Methods (Functions) [This should be moved to another function specific tutorial section]
1131
1226
1132
1227
Methods are just functions within a class. But because everything in Java must be within a class, every Java function is a method.
0 commit comments