Skip to content

Commit 1a108e0

Browse files
KhArtNJavaenhorse
authored andcommitted
Пример для finally
1 parent 6666fbb commit 1a108e0

1 file changed

Lines changed: 56 additions & 0 deletions

File tree

core.md

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -869,6 +869,62 @@ public class MainClass {
869869

870870
Метод `finalize()` вызывается перед тем как сборщик мусора будет проводить удаление объекта.
871871

872+
Пример:
873+
```java
874+
875+
public class MainClass {
876+
877+
public static void main(String args[]) {
878+
TestClass a = new TestClass();
879+
System.out.println("result of a.a() is " + a.a());
880+
a = null;
881+
System.gc(); // Принудительно зовём сборщик мусора
882+
a = new TestClass();
883+
System.out.println("result of a.a() is " + a.a());
884+
System.out.println("!!! done");
885+
}
886+
887+
}
888+
```
889+
890+
```java
891+
public class TestClass {
892+
893+
public int a() {
894+
try {
895+
System.out.println("!!! a() called");
896+
throw new Exception("");
897+
} catch (Exception e) {
898+
System.out.println("!!! Exception in a()");
899+
return 2;
900+
} finally {
901+
System.out.println("!!! finally in a() ");
902+
}
903+
}
904+
905+
@Override
906+
protected void finalize() throws Throwable {
907+
System.out.println("!!! finalize() called");
908+
super.finalize();
909+
}
910+
}
911+
```
912+
913+
Результат выполнения:
914+
915+
```
916+
!!! a() called
917+
!!! Exception in a()
918+
!!! finally in a()
919+
result of a.a() is 2
920+
!!! a() called
921+
!!! Exception in a()
922+
!!! finally in a()
923+
!!! finalize() called
924+
result of a.a() is 2
925+
!!! done
926+
```
927+
872928
[к оглавлению](#java-core)
873929

874930
## Расскажите про приведение типов. Что такое понижение и повышение типа?

0 commit comments

Comments
 (0)