Skip to main content

  | मौसम…

411 समाचार
Public archive edition · Attributed source reporting with original dates · AI drafts are excluded

411 REFERENCE · Wikibooks

Introduction to Programming Languages/Exceptions and Error Handling

Reference material by Wikibooks contributors. This retains its source identity and is not 411 news reporting.

Introduction During program execution, many things can go wrong: division by zero; invalid array access; null references; invalid casts; missing files; network failures. In older programming languages, this usually resulted in:Error message + program terminationModern languages such as Java introduced a more sophisticated mechanism: exception handling. This allows programs to: detect errors; react to them; attempt recovery; or terminate gracefully. Example: public class Test { public static void main(String[] args) { int i = Integer.parseInt(args[0]); int j = Integer.parseInt(args[1]); System.out.println(i / j); } }Execution:java Test 6 3Output:2 What Can Go Wrong? Missing Arguments java TestResult:ArrayIndexOutOfBoundsExceptionThis happens because:args[0]does not exist. Division by Zero java Test 6 0Result:ArithmeticExceptionBecause:6 / 0is an invalid operation. What Is an Exception? An exception is: an object; created when an error occurs; thrown during program execution. In Java:Exceptions are special objects Exceptions Are Objects Exception names are classes: NullPointerException ArithmeticException ArrayIndexOutOfBoundsException For example:NullPointerExceptionis a class. When an error occurs: Java creates an object of that class; throws that object; searches for somewhere capable of handling it. Common Exceptions +ExceptionCauseNullPointerExceptionUsing a null referenceArithmeticExceptionDivision by zeroClassCastExceptionInvalid array indexStringIndexOutOfBoundsExceptionInvalid castArrayIndexOutOfBoundsExceptionInvalid String index