Any program will work stably only if its source code is debugged and there are no conditions that can cause unforeseen situations. The process of catching possible failures is carried out at the programming stage. To do this, the developer takes into account all the expected outcomes and tries to limit the effect of the error so that it cannot disrupt the program or lead to its crash.
When Exception Handling May Be Required
Java , . , . , , - .
Java
? Java . , , . , . , , .
Java , .
, — . , , , , . , . , « ».
Java :
:
if (a == null)
throw new NullPointerException();
a , .. null. , , throw new NullPointerException().
Java . :
- Try. , . {}.
- Catch. .
- Finally. , , . try.
- Throw — Java .
- Throws — , . , Java . , — , .
try
Java , , . , . . , , .
Java try, . , , , .
:
try {
// ,
} catch (__1 _1) {
// , ;
} catch (__2 _2) {
// , ;
}
catch , , , , , , . .
Finally
, catch . , , . finally. , .
catch . , , try Cold. «Caught cold!» «Is that something to cheer about?». finally .
finally . . , , .
throw
Throw . :
throw new NewException();
NewException(). Java .
- , try, , .
throws
, , , . throws .
, . , , .
Try
Java 7 , try .
Java, . . AutoClosable. , try. , .
Java
. , , Java , .
— .
Exception, , . MyException — , — msg String.
public FullConstructors f, throws MyException. , f Java MyException. MyException, throw.
, , , . main , f() g() try, catch MyException. :
Java, .
Java, . , java.lang.Throwable. — Error Exception.
Error — Java. .
Exception. , , , RuntimeException. RuntimeException , . .
Java , , , :
- ArithmeticException. . — .
- ArrayIndexOutOfBoundsException — , .
- ArrayStoreException — .
- ClassCastException — .
- IllegalArgumentException — .
- NegativeArraySizeException — .
- NullPointerException — null.
- NumberFormatException — .
- UnsupportedOperationException — .
Java. :
- ClassNotFoundException — .
- IllegalAcccessException — .
- InterruptedException — .
- NoSuchFieldException — .
, , . , , .
NullPointerException. , , , null. . NullPointerException null. null.
ArrayIndexOutOfBoundsException. . , . , , . , . , .
Java — , . , , -.
, . .
Java , , . , .