Класс Throwable
Получение информации об исключении
Класс Throwable
Стек вызовов
Стек вызовов
Стек вызовов
Стек вызовов
Стек вызовов
Класс Throwable
Класс StackTraceElement
Элемент стека вызовов
Перебрасывание исключений
Перебрасывание исключений
Перебрасывание исключений
Не сцепленные исключения
Не сцепленные исключения
Класс Throwable
Класс Throwable
Сцепленные исключения
Сцепленные исключения
869.84K
Category: programmingprogramming

Исключения. Классы исключений

1.

2.

VI. Исключения
2. Классы исключений
2

3.

3

4. Класс Throwable

public
public class
class Throwable
Throwable implements
implements Serializable
Serializable {{
private
private String
String detailMessage;
detailMessage;
public
public Throwable()
Throwable() {{
fillInStackTrace();
fillInStackTrace();
}}
public
public Throwable(String
Throwable(String message)
message) {{
fillInStackTrace();
fillInStackTrace();
detailMessage
detailMessage == message;
message;
}}
public
public String
String getMessage()
getMessage() {{
return
return detailMessage;
detailMessage;
}}
public
public String
String getLocalizedMessage()
getLocalizedMessage() {{
return
return getMessage();
getMessage();
}}
}}
public
public String
String toString()
toString() {{
String
s
=
String s = getClass().getName();
getClass().getName();
String
message
String message == getLocalizedMessage();
getLocalizedMessage();
return
(message
!=
return (message != null)
null) ?? (s
(s ++ ":
": "" ++ message)
message) :: s;
s;
}}
4

5. Получение информации об исключении

public
public class
class ExceptionMethodsDemo
ExceptionMethodsDemo {{
public
public static
static void
void main(String[]
main(String[] args)
args) {{
try
try {{
throw
throw new
new Exception("My
Exception("My Exception");
Exception");
}} catch
catch (Exception
(Exception e)
e) {{
}}
}}
}}
System.out.println("Caught
System.out.println("Caught Exception");
Exception");
System.out.println("getMessage():"
System.out.println("getMessage():" ++ e.getMessage());
e.getMessage());
System.out.println("getLocalizedMessage():"
System.out.println("getLocalizedMessage():"
++ e.getLocalizedMessage());
e.getLocalizedMessage());
System.out.println("toString():"
System.out.println("toString():" ++ e);
e);
Caught
Caught Exception
Exception
getMessage():My
getMessage():My Exception
Exception
getLocalizedMessage():My
getLocalizedMessage():My Exception
Exception
toString():java.lang.Exception:
toString():java.lang.Exception: My
My Exception
Exception
5

6.

Стек вызовов
6

7.

Трассировка стека предоставляет информацию об истории
выполнения текущего потока и даёт список методов которые
вызывались до выбрасывания исключения. Нулевой элемент
представляет вершину стека, то есть последний вызванный метод
последовательности – метод в котором был создан и выброшен
объект Throwable. Последний элемент массива представляет низ
стека, то есть первый вызванный метод последовательности.
7

8. Класс Throwable

public
public class
class Throwable
Throwable implements
implements Serializable
Serializable {{
private
private StackTraceElement[]
StackTraceElement[] stackTrace;
stackTrace;
public
public void
void printStackTrace()
printStackTrace() {{
printStackTrace(System.err);
printStackTrace(System.err);
}}
public
public void
void printStackTrace(PrintStream
printStackTrace(PrintStream s)
s) {{
synchronized
synchronized (s)
(s) {{
s.println(this);
s.println(this);
StackTraceElement[]
StackTraceElement[] trace
trace == getOurStackTrace();
getOurStackTrace();
for
(int
i=0;
i
<
trace.length;
for (int i=0; i < trace.length; i++)
i++)
s.println("\tat
"
+
trace[i]);
s.println("\tat " + trace[i]);
}}
}}
Throwable
Throwable ourCause
ourCause == getCause();
getCause();
if
if (ourCause
(ourCause !=
!= null)
null)
ourCause.printStackTraceAsCause(s,
ourCause.printStackTraceAsCause(s, trace);
trace);
public
public StackTraceElement[]
StackTraceElement[] getStackTrace()
getStackTrace() {{
return
return (StackTraceElement[])
(StackTraceElement[]) getOurStackTrace().clone();
getOurStackTrace().clone();
}}
private
private synchronized
synchronized StackTraceElement[]
StackTraceElement[] getOurStackTrace()
getOurStackTrace() {{
}}
if
if (stackTrace
(stackTrace ==
== null)
null) {{
int
int depth
depth == getStackTraceDepth();
getStackTraceDepth();
stackTrace
stackTrace == new
new StackTraceElement[depth];
StackTraceElement[depth];
for
(int
i=0;
i
<
for (int i=0; i < depth;
depth; i++)
i++)
stackTrace[i]
=
getStackTraceElement(i);
stackTrace[i] = getStackTraceElement(i);
}}
return
return stackTrace;
stackTrace;
native
native int
int getStackTraceDepth();
getStackTraceDepth();
}}
8

9. Стек вызовов

public
public class
class StackTraceDemo
StackTraceDemo {{
static
static void
void methodA()
methodA() throws
throws Exception
Exception {{
throw
throw new
new Exception();
Exception();
}}
static
static void
void methodB()
methodB() throws
throws Exception
Exception {{
methodA();
methodA();
}}
static
static void
void methodC()
methodC() throws
throws Exception
Exception {{
methodB();
methodB();
}}
}}
...
...
9

10. Стек вызовов

public
public class
class StackTraceDemo
StackTraceDemo {{
...
...
public
public static
static void
void main(String[]
main(String[] args)
args) {{
try
try {{
methodA();
methodA();
}} catch
catch (Exception
(Exception e)
e) {{
for
for (StackTraceElement
(StackTraceElement ste
ste :: e.getStackTrace())
e.getStackTrace())
System.out.println(ste.getMethodName());
System.out.println(ste.getMethodName());
}}
System.out.println("--------------------------------");
System.out.println("--------------------------------");
try
try {{
methodB();
methodB();
}} catch
catch (Exception
(Exception e)
e) {{
for
for (StackTraceElement
(StackTraceElement ste
ste :: e.getStackTrace())
e.getStackTrace())
System.out.println(ste.getMethodName());
System.out.println(ste.getMethodName());
}}
}}
}}
System.out.println("--------------------------------");
System.out.println("--------------------------------");
try
try {{
methodC();
methodC();
}} catch
catch (Exception
(Exception e)
e) {{
for
for (StackTraceElement
(StackTraceElement ste
ste :: e.getStackTrace())
e.getStackTrace())
System.out.println(ste.getMethodName());
System.out.println(ste.getMethodName());
}}
10

11. Стек вызовов

methodA
methodA
main
main
--------------------------------------------------------------methodA
methodA
methodB
methodB
main
main
--------------------------------------------------------------methodA
methodA
methodB
methodB
methodC
methodC
main
main
11

12. Стек вызовов

public
public class
class AnotherStackTraceDemo
AnotherStackTraceDemo {{
...
...
public
public static
static void
void main(String[]
main(String[] args)
args) {{
try
try {{
methodA();
methodA();
}} catch
catch (Exception
(Exception e)
e) {{
e.printStackTrace(System.out);
e.printStackTrace(System.out);
}}
System.out.println("--------------------------------");
System.out.println("--------------------------------");
try
try {{
methodB();
methodB();
}} catch
catch (Exception
(Exception e)
e) {{
e.printStackTrace(System.out);
e.printStackTrace(System.out);
}}
}}
}}
System.out.println("--------------------------------");
System.out.println("--------------------------------");
try
try {{
methodC();
methodC();
}} catch
catch (Exception
(Exception e)
e) {{
e.printStackTrace(System.out);
e.printStackTrace(System.out);
}}
12

13. Стек вызовов

java.lang.Exception
java.lang.Exception
at
at classes.AnotherStackTraceDemo.methodA(AnotherStackTraceDemo.java:6)
classes.AnotherStackTraceDemo.methodA(AnotherStackTraceDemo.java:6)
at
at classes.AnotherStackTraceDemo.main(AnotherStackTraceDemo.java:19)
classes.AnotherStackTraceDemo.main(AnotherStackTraceDemo.java:19)
--------------------------------------------------------------java.lang.Exception
java.lang.Exception
at
at classes.AnotherStackTraceDemo.methodA(AnotherStackTraceDemo.java:6)
classes.AnotherStackTraceDemo.methodA(AnotherStackTraceDemo.java:6)
at
classes.AnotherStackTraceDemo.methodB(AnotherStackTraceDemo.java:10)
at classes.AnotherStackTraceDemo.methodB(AnotherStackTraceDemo.java:10)
at
at classes.AnotherStackTraceDemo.main(AnotherStackTraceDemo.java:26)
classes.AnotherStackTraceDemo.main(AnotherStackTraceDemo.java:26)
--------------------------------------------------------------java.lang.Exception
java.lang.Exception
at
at classes.AnotherStackTraceDemo.methodA(AnotherStackTraceDemo.java:6)
classes.AnotherStackTraceDemo.methodA(AnotherStackTraceDemo.java:6)
at
classes.AnotherStackTraceDemo.methodB(AnotherStackTraceDemo.java:10)
at classes.AnotherStackTraceDemo.methodB(AnotherStackTraceDemo.java:10)
at
at classes.AnotherStackTraceDemo.methodC(AnotherStackTraceDemo.java:14)
classes.AnotherStackTraceDemo.methodC(AnotherStackTraceDemo.java:14)
at
at classes.AnotherStackTraceDemo.main(AnotherStackTraceDemo.java:33)
classes.AnotherStackTraceDemo.main(AnotherStackTraceDemo.java:33)
13

14.

Элемент стека вызовов
14

15. Класс Throwable

public
public class
class Throwable
Throwable implements
implements Serializable
Serializable {{
public
public void
void setStackTrace(StackTraceElement[]
setStackTrace(StackTraceElement[] stackTrace)
stackTrace) {{
StackTraceElement[]
StackTraceElement[] defensiveCopy
defensiveCopy ==
(StackTraceElement[])
(StackTraceElement[]) stackTrace.clone();
stackTrace.clone();
for
(int
i
=
0;
i
<
defensiveCopy.length;
for (int i = 0; i < defensiveCopy.length; i++)
i++)
if
if (defensiveCopy[i]
(defensiveCopy[i] ==
== null)
null)
throw
throw new
new NullPointerException("stackTrace["
NullPointerException("stackTrace[" ++ ii ++ "]");
"]");
}}
}}
this.stackTrace
this.stackTrace == defensiveCopy;
defensiveCopy;
15

16. Класс StackTraceElement

public
public class
class StackTraceElement
StackTraceElement implements
implements java.io.Serializable
java.io.Serializable {{
private
private
private
private
private
private
private
private
String
String declaringClass;
declaringClass;
String
methodName;
String methodName;
String
String fileName;
fileName;
int
lineNumber;
int lineNumber;
public
public boolean
boolean isNativeMethod()
isNativeMethod() {{ return
return lineNumber
lineNumber ==
== -2;
-2; }}
public
public StackTraceElement(String
StackTraceElement(String declaringClass,
declaringClass, String
String methodName,
methodName, String
String fileName,
fileName, int
int lineNumber)
lineNumber) {{
if
if (declaringClass
(declaringClass ==
== null)
null)
throw
throw new
new NullPointerException("Declaring
NullPointerException("Declaring class
class is
is null");
null");
if
(methodName
==
null)
if (methodName == null)
throw
throw new
new NullPointerException("Method
NullPointerException("Method name
name is
is null");
null");
}}
}}
this.declaringClass
this.declaringClass
this.methodName
this.methodName
this.fileName
this.fileName
this.lineNumber
this.lineNumber
==
==
==
==
declaringClass;
declaringClass;
methodName;
methodName;
fileName;
fileName;
lineNumber;
lineNumber;
public
public String
String toString()
toString() {{
return
return getClassName()
getClassName() ++ "."
"." ++ methodName
methodName ++
(isNativeMethod()
(isNativeMethod() ?? "(Native
"(Native Method)"
Method)" ::
(fileName
(fileName !=
!= null
null &&
&& lineNumber
lineNumber >=
>= 00 ??
"("
+
fileName
+
":"
+
lineNumber
"(" + fileName + ":" + lineNumber ++ ")"
")"
(fileName
!=
null
?
"("+fileName+")"
(fileName != null ? "("+fileName+")" ::
}}
...
...
C
::
"(Unknown
"(Unknown Source)")));
Source)")));
Класс StackTraceElement используется для представления стекового кадра в трассировке
стека. Стековый кадр на вершине стека представляет точку в которой трассировка стека
была создана. Остальные стековые кадры представляют вызовы методов. В классе есть
поля для имени класса вызванного метода, названия метода, имени файла и строки в
файле.
16

17. Элемент стека вызовов

public
public class
class StackTraceElementDemo
StackTraceElementDemo {{
public
public static
static void
void main(String[]
main(String[] args)
args) {{
try
try {{
methodA();
methodA();
}} catch
catch (Throwable
(Throwable e)
e) {{
}}
}}
e.printStackTrace();
e.printStackTrace();
public
public static
static void
void methodA()
methodA() throws
throws RuntimeException
RuntimeException {{
RuntimeException
RuntimeException tt == new
new RuntimeException("This
RuntimeException("This is
is aa new
new Exception...");
Exception...");
StackTraceElement[]
StackTraceElement[] trace
trace == new
new StackTraceElement[]
StackTraceElement[] {{ new
new StackTraceElement(
StackTraceElement(
"ClassName",
"ClassName", "methodName",
"methodName", "fileName",
"fileName", 5)
5) };
};
}}
}}
t.setStackTrace(trace);
t.setStackTrace(trace);
throw
throw t;
t;
java.lang.RuntimeException:
java.lang.RuntimeException: This
This is
is aa new
new Exception...
Exception...
at
at ClassName.methodName(fileName:5)
ClassName.methodName(fileName:5)
17

18.

Перебрасывание исключений из блока catch
18

19.

Во время обработки исключения блоком catch обрабатываемое
исключение может быть переброшено. В этом случае трассировка
стека будет сохранена если специально её не менять. Такой подход
может иногда использоваться для локального логирования.
19

20. Перебрасывание исключений

public
public class
class RethrowingDemo
RethrowingDemo {{
public
public static
static void
void methodA()
methodA() throws
throws Exception
Exception {{
System.out.println("Originating
System.out.println("Originating the
the exception
exception in
in methodA()");
methodA()");
throw
throw new
new Exception("Thrown
Exception("Thrown from
from methodA()");
methodA()");
}}
public
public static
static void
void methodB()
methodB() throws
throws Exception
Exception {{
try
try {{
methodA();
methodA();
}} catch
catch (Exception
(Exception e)
e) {{
System.out.println("Inside
System.out.println("Inside methodB");
methodB");
e.printStackTrace(System.out);
e.printStackTrace(System.out);
throw
throw e;
e;
}}
}}
}}
public
public static
static void
void methodC()
methodC() throws
throws Exception
Exception {{
try
try {{
methodA();
methodA();
}} catch
catch (Exception
(Exception e)
e) {{
System.out.println("Inside
System.out.println("Inside methodC");
methodC");
e.printStackTrace(System.out);
e.printStackTrace(System.out);
throw
throw (Exception)
(Exception) e.fillInStackTrace();
e.fillInStackTrace();
}}
}}
20

21. Перебрасывание исключений

public
public class
class RethrowingDemo
RethrowingDemo {{
public
public static
static void
void main(String[]
main(String[] args)
args) {{
try
try {{
methodB();
methodB();
}} catch
catch (Exception
(Exception e)
e) {{
System.out.println("Caught
System.out.println("Caught in
in main");
main");
e.printStackTrace(System.out);
e.printStackTrace(System.out);
}}
System.out.println();
System.out.println();
}}
try
try {{
methodC();
methodC();
}} catch
catch (Exception
(Exception e)
e) {{
System.out.println("Caught
System.out.println("Caught in
in main");
main");
e.printStackTrace(System.out);
e.printStackTrace(System.out);
}}
}}
21

22. Перебрасывание исключений

Originating
Originating the
the exception
exception in
in methodA()
methodA()
Inside
Inside methodB
methodB
java.lang.Exception:
java.lang.Exception: Thrown
Thrown from
from methodA()
methodA()
at
classes.RethrowingDemo.methodA(RethrowingDemo.java:7)
at classes.RethrowingDemo.methodA(RethrowingDemo.java:7)
at
at classes.RethrowingDemo.methodB(RethrowingDemo.java:12)
classes.RethrowingDemo.methodB(RethrowingDemo.java:12)
at
at classes.RethrowingDemo.main(RethrowingDemo.java:32)
classes.RethrowingDemo.main(RethrowingDemo.java:32)
Caught
Caught in
in main
main
java.lang.Exception:
java.lang.Exception: Thrown
Thrown from
from methodA()
methodA()
at
classes.RethrowingDemo.methodA(RethrowingDemo.java:7)
at classes.RethrowingDemo.methodA(RethrowingDemo.java:7)
at
at classes.RethrowingDemo.methodB(RethrowingDemo.java:12)
classes.RethrowingDemo.methodB(RethrowingDemo.java:12)
at
at classes.RethrowingDemo.main(RethrowingDemo.java:32)
classes.RethrowingDemo.main(RethrowingDemo.java:32)
Originating
Originating the
the exception
exception in
in methodA()
methodA()
Inside
Inside methodC
methodC
java.lang.Exception:
java.lang.Exception: Thrown
Thrown from
from methodA()
methodA()
at
at classes.RethrowingDemo.methodA(RethrowingDemo.java:7)
classes.RethrowingDemo.methodA(RethrowingDemo.java:7)
at
at classes.RethrowingDemo.methodC(RethrowingDemo.java:22)
classes.RethrowingDemo.methodC(RethrowingDemo.java:22)
at
at classes.RethrowingDemo.main(RethrowingDemo.java:38)
classes.RethrowingDemo.main(RethrowingDemo.java:38)
Caught
Caught in
in main
main
java.lang.Exception:
java.lang.Exception: Thrown
Thrown from
from methodA()
methodA()
at
at classes.RethrowingDemo.methodC(RethrowingDemo.java:26)
classes.RethrowingDemo.methodC(RethrowingDemo.java:26)
at
at classes.RethrowingDemo.main(RethrowingDemo.java:38)
classes.RethrowingDemo.main(RethrowingDemo.java:38)
22

23.

Сцепленные исключения
23

24.

Собирание исключений в цепочку или оборачивание исключений
позволяет ассоциировать с одним исключением другое которое
описывает причину его появления. Такой подход позволяет
перебрасывать перехваченное исключение обернув его другим
исключением. Таким образом можно добиться того чтобы метод
выбрасывал исключения определённые на том же самом уровне
абстракции, но без потери информации с нижних уровней. Кроме того
оборачивание исключений
позволяет обернуть контролируемое
исключение неконтролируемым если программа не может
восстановиться после выбрасывания контролируемого исключения.
24

25. Не сцепленные исключения

public
public class
class NoChainedExceptionDemo
NoChainedExceptionDemo {{
public
public static
static void
void methodA()
methodA() throws
throws Exception
Exception {{
System.out.println("Originating
System.out.println("Originating the
the exception
exception in
in methodA()");
methodA()");
throw
throw new
new Exception("Thrown
Exception("Thrown from
from methodA()");
methodA()");
}}
public
public static
static void
void methodB()
methodB() throws
throws Exception
Exception {{
try
try {{
methodA();
methodA();
}} catch
catch (Exception
(Exception e)
e) {{
System.out.println("Throwing
System.out.println("Throwing new
new exception
exception in
in methodB()");
methodB()");
throw
new
Exception("Thrown
from
methodB()");
throw new Exception("Thrown from methodB()");
}}
}}
public
public static
static void
void methodC()
methodC() {{
try
try {{
methodB();
methodB();
}} catch
catch (Exception
(Exception e)
e) {{
System.out.println("Throwing
System.out.println("Throwing new
new exception
exception in
in methodC()");
methodC()");
throw
throw new
new RuntimeException("Thrown
RuntimeException("Thrown from
from methodC()");
methodC()");
}}
}}
}}
public
public static
static void
void main(String[]
main(String[] args)
args) {{
methodC();
methodC();
}}
25

26. Не сцепленные исключения

Originating
Originating the
the exception
exception in
in methodA()
methodA()
Throwing
Throwing new
new exception
exception in
in methodB()
methodB()
Throwing
Throwing new
new exception
exception in
in methodC()
methodC()
Exception
Exception in
in thread
thread "main"
"main" java.lang.RuntimeException:
java.lang.RuntimeException: Thrown
Thrown from
from methodC()
methodC()
at
classes.NoChainedExceptionDemo.methodC(NoChainedExceptionDemo.java:27)
at classes.NoChainedExceptionDemo.methodC(NoChainedExceptionDemo.java:27)
at
at classes.NoChainedExceptionDemo.main(NoChainedExceptionDemo.java:32)
classes.NoChainedExceptionDemo.main(NoChainedExceptionDemo.java:32)
26

27. Класс Throwable

public
public class
class Throwable
Throwable implements
implements Serializable
Serializable {{
private
private Throwable
Throwable cause
cause == this;
this;
public
public Throwable
Throwable getCause()
getCause() {{
return
return (cause==this
(cause==this ?? null
null :: cause);
cause);
}}
public
Throwable
cause)
public Throwable(String
Throwable(String message,
message, Throwable
Throwable cause
cause) {{
fillInStackTrace();
fillInStackTrace();
detailMessage
detailMessage == message;
message;
this.cause
=
cause
this.cause
this.cause == cause;
cause;
}}
}}
Throwable cause
public
cause)
public synchronized
synchronized Throwable
Throwable initCause(Throwable
initCause(Throwable
cause) {{
if
if (this.cause
(this.cause !=
!= this)
this)
throw
throw new
new IllegalStateException("Can't
IllegalStateException("Can't overwrite
overwrite cause");
cause");
if
(cause
==
this)
if (cause == this)
throw
throw new
new IllegalArgumentException("Self-causation
IllegalArgumentException("Self-causation not
not permitted");
permitted");
final
this.cause
this.cause
cause;
this.cause === cause
cause;
final
return
return this;
this;
final
}}
C
Класс Throwable включает поле cause типа Throwable для хранения ссылки на другое
исключение которое является его причиной. Причину исключения можно задать либо в
конструкторе или с помощью метода initCause(Throwable). Классы потомки Throwable могут
определить конструктор принимающий Throwable и делегирующий (возможно не напрямую)
задание причины одному из конструкторов Throwable. При выводе трассировки стека
исключения выводится и трассировка стека для исключения которое являлось его
причиной.
27

28. Класс Throwable

public
public class
class Throwable
Throwable implements
implements Serializable
Serializable {{
public
public void
void printStackTrace(PrintStream
printStackTrace(PrintStream s)
s) {{
synchronized
synchronized (s)
(s) {{
s.println(this);
s.println(this);
StackTraceElement[]
StackTraceElement[] trace
trace == getOurStackTrace();
getOurStackTrace();
for
(int
i=0;
i
<
trace.length;
for (int i=0; i < trace.length; i++)
i++)
s.println("\tat
s.println("\tat "" ++ trace[i]);
trace[i]);
}}
}}
Throwable
Throwable ourCause
ourCause == getCause();
getCause();
if
(ourCause
!=
null)
if (ourCause != null)
printStackTraceAsCause
ourCause.printStackTraceAsCause(s,
trace);
ourCause.printStackTraceAsCause(s,
trace);
private
printStackTraceAsCause(PrintStream
private void
void printStackTraceAsCause
printStackTraceAsCause(PrintStream s,
s, StackTraceElement[]
StackTraceElement[] causedTrace)
causedTrace) {{
StackTraceElement[]
StackTraceElement[] trace
trace == getOurStackTrace();
getOurStackTrace();
int
m
=
trace.length-1,
n
=
causedTrace.length-1;
int m = trace.length-1, n = causedTrace.length-1;
while
{{
while (m
(m >=
>= 00 &&
&& nn >=0
>=0 &&
&& trace[m].equals(causedTrace[n]))
trace[m].equals(causedTrace[n]))
final
m--;
m--; n--;
n--;
final
}}
final
int
int framesInCommon
framesInCommon == trace.length
trace.length -- 11 -- m;
m;
s.println("Caused
s.println("Caused by:
by: "" ++ this);
this);
for
for (int
(int i=0;
i=0; ii <=
<= m;
m; i++)
i++)
s.println("\tat
s.println("\tat "" ++ trace[i]);
trace[i]);
if
(framesInCommon
!=
0)
if (framesInCommon != 0)
s.println("\t...
s.println("\t... "" ++ framesInCommon
framesInCommon ++ "" more");
more");
}}
}}
Throwable
Throwable ourCause
ourCause == getCause();
getCause();
if
if (ourCause
(ourCause !=
!= null)
null)
ourCause.printStackTraceAsCause(s,
ourCause.printStackTraceAsCause(s, trace);
trace);
public
public Throwable
Throwable getCause()
getCause() {{
return
return (cause==this
(cause==this ?? null
null :: cause);
cause);
}}
28

29. Сцепленные исключения

public
public class
class ChainedExceptionDemo
ChainedExceptionDemo {{
public
public static
static void
void methodA()
methodA() throws
throws Exception
Exception {{
System.out.println("Originating
System.out.println("Originating the
the exception
exception in
in methodA()");
methodA()");
throw
throw new
new Exception("Thrown
Exception("Thrown from
from methodA()");
methodA()");
}}
public
public static
static void
void methodB()
methodB() throws
throws Exception
Exception {{
try
try {{
methodA();
methodA();
}} catch
catch (Exception
(Exception e)
e) {{
System.out.println("Throwing
System.out.println("Throwing new
new exception
exception in
in methodB()");
methodB()");
throw
new
Exception("Thrown
from
methodB()",
e);
throw new Exception("Thrown from methodB()", e);
}}
}}
public
public static
static void
void methodC()
methodC() {{
try
try {{
methodB();
methodB();
}} catch
catch (Exception
(Exception e)
e) {{
System.out.println("Throwing
System.out.println("Throwing new
new exception
exception in
in methodC()");
methodC()");
throw
throw new
new RuntimeException("Thrown
RuntimeException("Thrown from
from methodC()",
methodC()", e);
e);
}}
}}
}}
public
public static
static void
void main(String[]
main(String[] args)
args) {{
methodC();
methodC();
}}
29

30. Сцепленные исключения

Originating
Originating the
the exception
exception in
in methodA()
methodA()
Throwing
Throwing new
new exception
exception in
in methodB()
methodB()
Throwing
Throwing new
new exception
exception in
in methodC()
methodC()
Exception
Exception in
in thread
thread "main"
"main" java.lang.RuntimeException:
java.lang.RuntimeException: Thrown
Thrown from
from methodC()
methodC()
at
classes.ChainedExceptionDemo.methodC(ChainedExceptionDemo.java:27)
at classes.ChainedExceptionDemo.methodC(ChainedExceptionDemo.java:27)
at
at classes.ChainedExceptionDemo.main(ChainedExceptionDemo.java:32)
classes.ChainedExceptionDemo.main(ChainedExceptionDemo.java:32)
Caused
Caused by:
by: java.lang.Exception:
java.lang.Exception: Thrown
Thrown from
from methodB()
methodB()
at
at classes.ChainedExceptionDemo.methodB(ChainedExceptionDemo.java:18)
classes.ChainedExceptionDemo.methodB(ChainedExceptionDemo.java:18)
at
at classes.ChainedExceptionDemo.methodC(ChainedExceptionDemo.java:24)
classes.ChainedExceptionDemo.methodC(ChainedExceptionDemo.java:24)
...
... 11 more
more
Caused
Caused by:
by: java.lang.Exception:
java.lang.Exception: Thrown
Thrown from
from methodA()
methodA()
at
at classes.ChainedExceptionDemo.methodA(ChainedExceptionDemo.java:10)
classes.ChainedExceptionDemo.methodA(ChainedExceptionDemo.java:10)
at
at classes.ChainedExceptionDemo.methodB(ChainedExceptionDemo.java:15)
classes.ChainedExceptionDemo.methodB(ChainedExceptionDemo.java:15)
...
... 22 more
more
30
English     Русский Rules