Java: exceptions and their handling

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 exceptions




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. , .

java exception handling




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 , .

— .

java exceptions list




Exception, , . MyException — , — msg String.

public FullConstructors f, throws MyException. , f Java MyException. MyException, throw.

, , , . main , f() g() try, catch MyException. :

throw java exceptions




Java, .

Java, . , java.lang.Throwable. — Error Exception.

throw java exception




Error — Java. .

Exception. , , , RuntimeException. RuntimeException , . .

Java , , , :

  • ArithmeticException. . — .
  • ArrayIndexOutOfBoundsException — , .
  • ArrayStoreException — .
  • ClassCastException — .
  • IllegalArgumentException — .
  • NegativeArraySizeException — .
  • NullPointerException — null.
  • NumberFormatException — .
  • UnsupportedOperationException — .

Java. :

  • ClassNotFoundException — .
  • IllegalAcccessException — .
  • InterruptedException — .
  • NoSuchFieldException — .

, , . , , .

java exception types




NullPointerException. , , , null. . NullPointerException null. null.

ArrayIndexOutOfBoundsException. . , . , , . , . , .

Java — , . , , -.

java error exceptions




, . .

Java , , . , .




All Articles