Java/construction/try catch

Материал из Энциклопедия о программировании
Перейти к: навигация, поиск

try catch — construction for exception trapping.

When executing Java code, different errors can occur: coding errors made by the programmer, errors due to wrong input, or other unforeseeable things.

When an error occurs, Java will normally stop and generate an error message. The technical term for this is: Java will throw an exception (throw an error).

Содержание

Blocks

  • The try statement allows you to define a block of code to be tested for errors while it is being executed.
  • The catch statement allows you to define a block of code to be executed, if an error occurs in the try block.

Syntax

try {
  //  Block of code to try
}
catch (Exception e) {
  //  Block of code to handle errors
}

Examples

try {
	int a = 10 / 0;
} catch (ArithmeticException e) {
	System.out.println("Exception class/type: " + e.getClass() + ", exception message: " + e.getMessage());
} catch (Exception e) {
	System.out.println("Exception class/type: " + e.getClass() + ", exception message: " + e.getMessage());
} finally {
	System.out.println("The 'try catch' block is finished.");
}

Throw exception:

String errorMessage = null;
try {
	throw new Exception("Let's throw some exception message here");
} catch(Exception e) {
	System.out.println("In Exception block.");
	errorMessage = e.getMessage();
} finally {
	System.out.println(errorMessage);
}

Links