Замена простой проверки
Перехватывание и игнорирование
Деструктивная обёртка
Недеструктивная обёртка
Возвращение null
Возвращение null
Возвращение null
Логирование и перебрасывание
Логирование и перебрасывание
653.35K
Категория: ПрограммированиеПрограммирование

Исключения. Antipatterns. Замена проверки исключением

1.

2.

VI. Исключения
4. Antipatterns
2

3.

Замена проверки исключением
3

4. Замена простой проверки

public
public class
class TestReplacementDemo
TestReplacementDemo {{
public
public static
static void
void main(String[]
main(String[] args)
args) {{
String[]
String[] names
names == {{ "Harry
"Harry Hacker",
Hacker", "Tonny
"Tonny Tester",
Tester", "Eve
"Eve Engineer"
Engineer" };
};
long
long now
now == System.currentTimeMillis();
System.currentTimeMillis();
for
for (int
(int ii == 0;
0; ii << 100000000;
100000000; i++)
i++) {{
if
if (3
(3 << names.length)
names.length) {{
}}
}}
System.out.println(names[3]);
System.out.println(names[3]);
System.out.println("Time
System.out.println("Time using
using length
length check:
check: "" ++ (System.currentTimeMillis()
(System.currentTimeMillis() -- now)
now) ++ "" ms");
ms");
now
now == System.currentTimeMillis();
System.currentTimeMillis();
for
for (int
(int ii == 0;
0; ii << 100000000;
100000000; i++)
i++) {{
try
try {{
System.out.println(names[3]);
System.out.println(names[3]);
}} catch
catch (ArrayIndexOutOfBoundsException
(ArrayIndexOutOfBoundsException e)
e) {{
}}
}}
}}
Time
Time
Time
Time
}}
System.out.println("Time
System.out.println("Time using
using exceptions:
exceptions: "" ++ (System.currentTimeMillis()
(System.currentTimeMillis() -- now)
now) ++ "" ms");
ms");
using
using
using
using
length
length check:
check: 141
141 ms
ms
exceptions:
232765
exceptions: 232765 ms
ms
4

5.

Перехватывание и игнорирование
5

6. Перехватывание и игнорирование

public
public class
class CatchAndIgnore
CatchAndIgnore {{
public
public static
static void
void main(String[]
main(String[] args)
args) {{
String[]
String[] names
names == {{ "I:\\FileIO\\lineFile.txt",
"I:\\FileIO\\lineFile.txt", "I:\\noSuchDir\\noSuchFile"
"I:\\noSuchDir\\noSuchFile" };
};
}}
for
for (String
(String name
name :: names)
names) {{
printFirstLine(name);
printFirstLine(name);
}}
private
private static
static void
void printFirstLine(String
printFirstLine(String fileName)
fileName) {{
try
try {{
BufferedReader
BufferedReader br
br == new
new BufferedReader(new
BufferedReader(new FileReader(fileName));
FileReader(fileName));
System.out.print(br.readLine());
System.out.print(br.readLine());
}}
}}
}}
catch
catch (IOException
(IOException e)
e) {{
}}
6

7.

Деструктивная обёртка
7

8.

class
class MyException
MyException extends
extends RuntimeException
RuntimeException {{
public
public MyException(String
MyException(String message)
message) {{
super(message);
super(message);
}}
}}
public
public MyException(String
MyException(String message,
message, Throwable
Throwable cause)
cause) {{
super(message,
super(message, cause);
cause);
}}
8

9. Деструктивная обёртка

public
public class
class DestructiveWrappingDemo
DestructiveWrappingDemo {{
public
public static
static void
void main(String[]
main(String[] args)
args) {{
String[]
String[] names
names == {{ "I:\\FileIO\\lineFile.txt",
"I:\\FileIO\\lineFile.txt", "I:\\noSuchDir\\noSuchFile"
"I:\\noSuchDir\\noSuchFile" };
};
}}
for
for (String
(String name
name :: names)
names) {{
try
try {{
writeLine(name,
writeLine(name, "Hello
"Hello World!");
World!");
}} catch
catch (IOException
(IOException e)
e) {{
throw
throw new
new MyException("Hello:
MyException("Hello: something
something bad
bad has
has happened
happened .....
..... ");
");
}}
}}
private
private static
static void
void writeLine(String
writeLine(String fileName,
fileName, String
String line)
line)
throws
IOException
{
throws IOException {
}}
}}
Writer
Writer wr
wr == new
new FileWriter(fileName);
FileWriter(fileName);
wr.write(line);
wr.write(line);
wr.flush();
wr.flush();
Exception
Exception in
in thread
thread "main"
"main" antipatterns.MyException:
antipatterns.MyException: Hello:
Hello: something
something bad
bad has
has happened
happened .....
.....
at
at antipatterns.DestructiveWrappingDemo.main(DestructiveWrappingDemo.java:18)
antipatterns.DestructiveWrappingDemo.main(DestructiveWrappingDemo.java:18)
9

10. Недеструктивная обёртка

public
public class
class DestructiveWrappingDemo
DestructiveWrappingDemo {{
public
public static
static void
void main(String[]
main(String[] args)
args) {{
String[]
String[] names
names == {{ "I:\\FileIO\\lineFile.txt",
"I:\\FileIO\\lineFile.txt", "I:\\noSuchDir\\noSuchFile"
"I:\\noSuchDir\\noSuchFile" };
};
}}
for
for (String
(String name
name :: names)
names) {{
try
try {{
writeLine(name,
writeLine(name, "Hello
"Hello World!");
World!");
}} catch
(IOException
e)
{
catch (IOException e) {
throw
throw new
new MyException("Hello:
MyException("Hello: something
something bad
bad has
has happened
happened .....
..... ",
", e);
e);
}}
}}
private
private static
static void
void writeLine(String
writeLine(String fileName,
fileName, String
String line)
line)
throws
throws IOException
IOException {{
}}
}}
Writer
Writer wr
wr == new
new FileWriter(fileName);
FileWriter(fileName);
wr.write(line);
wr.write(line);
wr.flush();
wr.flush();
Exception
Exception in
in thread
thread "main"
"main" antipatterns.MyException:
antipatterns.MyException: Hello:
Hello: something
something bad
bad has
has happened
happened .....
.....
at
at antipatterns.DestructiveWrappingDemo.main(DestructiveWrappingDemo.java:19)
antipatterns.DestructiveWrappingDemo.main(DestructiveWrappingDemo.java:19)
Caused
Caused by:
by: java.io.FileNotFoundException:
java.io.FileNotFoundException: I:\noSuchDir\noSuchFile
I:\noSuchDir\noSuchFile (The
(The system
system cannot
cannot find
find the
the path
path specified)
specified)
at
at java.io.FileOutputStream.open(Native
java.io.FileOutputStream.open(Native Method)
Method)
at
java.io.FileOutputStream.<init>(Unknown
at java.io.FileOutputStream.<init>(Unknown Source)
Source)
at
java.io.FileOutputStream.<init>(Unknown
Source)
at java.io.FileOutputStream.<init>(Unknown Source)
at
at java.io.FileWriter.<init>(Unknown
java.io.FileWriter.<init>(Unknown Source)
Source)
at
at antipatterns.DestructiveWrappingDemo.writeLine(DestructiveWrappingDemo.java:27)
antipatterns.DestructiveWrappingDemo.writeLine(DestructiveWrappingDemo.java:27)
at
at antipatterns.DestructiveWrappingDemo.main(DestructiveWrappingDemo.java:16)
antipatterns.DestructiveWrappingDemo.main(DestructiveWrappingDemo.java:16)
10

11.

Перехватывание и возвращение null
11

12. Возвращение null

public
public class
class CatchReturnNull
CatchReturnNull {{
public
public static
static void
void main(String[]
main(String[] args)
args) {{
String
String line
line == readFirstLine("I:\\noSuchDir\\noSuchFile");
readFirstLine("I:\\noSuchDir\\noSuchFile");
}}
if
if (line
(line ==
== null)
null) {{
System.out.println("File
System.out.println("File is
is empty");
empty");
}}
else
else {{
System.out.println("First
System.out.println("First line
line in
in file:
file: "" ++ line);
line);
}}
private
private static
static String
String readFirstLine(String
readFirstLine(String fileName)
fileName) {{
try
try {{
}}
}}
}}
BufferedReader
BufferedReader br
br == new
new BufferedReader(new
BufferedReader(new FileReader(fileName));
FileReader(fileName));
return
return br.readLine();
br.readLine();
catch
catch (IOException
(IOException e)
e) {{
return
return null;
null;
}}
File
File is
is empty
empty
12

13.

Возвращение null для неподдерживаемой
операции
13

14. Возвращение null

public
public class
class UnsupOpReturnNull
UnsupOpReturnNull {{
public
public static
static void
void main(String[]
main(String[] args)
args) {{
}}
}}
SingletonStringMap
SingletonStringMap map=
map= new
new SingletonStringMap("firstName",
SingletonStringMap("firstName", "Alice");
"Alice");
System.out.println(map);
System.out.println(map);
map.put("lastName",
map.put("lastName", "Coder");
"Coder");
System.out.println(map.get("lastName").trim());
System.out.println(map.get("lastName").trim());
class
class SingletonStringMap
SingletonStringMap {{
private
private final
final String
String k;
k;
private
private final
final String
String v;
v;
SingletonStringMap(String
SingletonStringMap(String key,
key, String
String value)
value) {{
kk == key;
key;
vv == value;
value;
}}
public
public
public
public
public
public
public
public
public
public
public
public
public
public
}}
int
int size()
size() {return
{return 1;}
1;}
boolean
isEmpty()
{return
boolean isEmpty() {return false;}
false;}
boolean
boolean containsKey(Object
containsKey(Object key)
key) {return
{return eq(key,
eq(key, k);}
k);}
boolean
boolean containsValue(Object
containsValue(Object value)
value) {return
{return eq(value,
eq(value, v);}
v);}
String
String get(String
get(String key)
key) {return
{return (eq(key,
(eq(key, k)
k) ?? vv :: null);}
null);}
String
put(String
key,
String
value)
{return
null;}
String put(String key, String value) {return null;}
String
String toString()
toString() {return
{return "["
"[" ++ kk ++ ","
"," ++ vv +"]";}
+"]";}
private
private static
static boolean
boolean eq(Object
eq(Object o1,
o1, Object
Object o2)
o2) {{
return
return (o1==null
(o1==null ?? o2==null
o2==null :: o1.equals(o2));
o1.equals(o2));
}}
14

15. Возвращение null

[firstName,Alice]
[firstName,Alice]
Exception
Exception in
in thread
thread "main"
"main" java.lang.NullPointerException
java.lang.NullPointerException
at
at antipatterns.UnsupOpReturnNull.main(UnsupOpReturnNull.java:10)
antipatterns.UnsupOpReturnNull.main(UnsupOpReturnNull.java:10)
15

16.

Логирование и перебрасывание
16

17. Логирование и перебрасывание

class
class SomeClass
SomeClass {{
private
private static
static Logger
Logger logger
logger == Logger.getLogger(SomeClass.class);
Logger.getLogger(SomeClass.class);
public
public void
void methodA()
methodA() throws
throws IOException
IOException {{
try
try {{
throw
throw new
new IOException();
IOException();
}} catch
catch (IOException
(IOException e)
e) {{
logger.error("Error!",
logger.error("Error!", e);
e);
throw
throw e;
e;
}}
}}
public
public void
void methodB()
methodB() throws
throws IOException
IOException {{
try
try {{
methodA();
methodA();
}} catch
catch (IOException
(IOException e)
e) {{
logger.error("Error!",
logger.error("Error!", e);
e);
throw
throw e;
e;
}}
}}
}}
public
public void
void methodC()
methodC() throws
throws IOException
IOException {{
try
try {{
methodB();
methodB();
}} catch
catch (IOException
(IOException e)
e) {{
logger.error("Error!",
logger.error("Error!", e);
e);
System.out.println("Handle
System.out.println("Handle Exception
Exception here.....");
here.....");
}}
}}
17

18. Логирование и перебрасывание

00 [main]
[main] ERROR
ERROR antipatterns.SomeClass
antipatterns.SomeClass -- Error!
Error!
java.io.IOException
java.io.IOException
at
at antipatterns.SomeClass.methodA(LogAndRethrowDemo.java:23)
antipatterns.SomeClass.methodA(LogAndRethrowDemo.java:23)
at
at antipatterns.SomeClass.methodB(LogAndRethrowDemo.java:32)
antipatterns.SomeClass.methodB(LogAndRethrowDemo.java:32)
at
antipatterns.SomeClass.methodC(LogAndRethrowDemo.java:41)
at antipatterns.SomeClass.methodC(LogAndRethrowDemo.java:41)
at
at antipatterns.LogAndRethrowDemo.main(LogAndRethrowDemo.java:13)
antipatterns.LogAndRethrowDemo.main(LogAndRethrowDemo.java:13)
00 [main]
[main] ERROR
ERROR antipatterns.SomeClass
antipatterns.SomeClass -- Error!
Error!
java.io.IOException
java.io.IOException
at
at antipatterns.SomeClass.methodA(LogAndRethrowDemo.java:23)
antipatterns.SomeClass.methodA(LogAndRethrowDemo.java:23)
at
antipatterns.SomeClass.methodB(LogAndRethrowDemo.java:32)
at antipatterns.SomeClass.methodB(LogAndRethrowDemo.java:32)
at
at antipatterns.SomeClass.methodC(LogAndRethrowDemo.java:41)
antipatterns.SomeClass.methodC(LogAndRethrowDemo.java:41)
at
at antipatterns.LogAndRethrowDemo.main(LogAndRethrowDemo.java:13)
antipatterns.LogAndRethrowDemo.main(LogAndRethrowDemo.java:13)
00 [main]
[main] ERROR
ERROR antipatterns.SomeClass
antipatterns.SomeClass -- Error!
Error!
java.io.IOException
java.io.IOException
at
at antipatterns.SomeClass.methodA(LogAndRethrowDemo.java:23)
antipatterns.SomeClass.methodA(LogAndRethrowDemo.java:23)
at
antipatterns.SomeClass.methodB(LogAndRethrowDemo.java:32)
at antipatterns.SomeClass.methodB(LogAndRethrowDemo.java:32)
at
at antipatterns.SomeClass.methodC(LogAndRethrowDemo.java:41)
antipatterns.SomeClass.methodC(LogAndRethrowDemo.java:41)
at
at antipatterns.LogAndRethrowDemo.main(LogAndRethrowDemo.java:13)
antipatterns.LogAndRethrowDemo.main(LogAndRethrowDemo.java:13)
Handle
Handle Exception
Exception here.....
here.....
18
English     Русский Правила