Exception handling

An exception or exception situation ( engl. exception), in computer technology, a method, information about specific program states - passing them on to other program levels for further treatment - mostly error conditions.

Can be used in a program, for example, a memory request can not be satisfied, triggers a memory request exception. A computer program can be used to address this problem, execute this defined algorithms that resolve or report the error.

Structured Exception Handling

The most important role in programming is played by the structured exception handling (English structured exception handling, short SEH ), a technique that keeps it separate from application code for exception handling code. Instead of a return value indicating the success example to test with each function call, and respond to it, you can let throw an exception that function in exceptional situations, which carries all the information necessary for problem identification and treatment in itself.

Since the causative function (or the function that detects the problem) the error may not be adequately addressed in their context, the exception is passed back as long to calling functions, until finally a the exception " catches". This one builds usefully At a point in the code where it is foreseeable, which may have consequences for this exception and how it responds best ( for example, new user input, program termination, termination of a particular operation ). In addition, each section of code that can do anything with respect to exception handling, free from error handling routines.

Another decisive advantage over the error handling return values ​​is that an exception can not be ignored. A programmer might forget to check the return value, but an exception is ever passed back - in extreme cases, until it arrives in the program- starting function, if the programmer has failed to intercept it. In this case, which often leads to a program abort. This may seem subtle, but the result is usually that programs that run stable despite error handling via exceptions also run really stable. In contrast, ignoring an error value can be many times have no drastic consequences and eventually the program could but may produce unexpected results.

Programming languages ​​that support exception handling, are, for example, C , Java, C #, Object Pascal, Visual Basic.Net, PHP (version 5 ), Python, Common Lisp, Ruby, Eiffel, Ada and Objective CAML.

Different hardware architectures ( such as the IA- 32 architecture of Intel) support an exception handling at the hardware level by the operating system. Here are triggered by certain invalid operations software interrupts, which cause a jump in the privileged kernel. This can then exit the basis of the exception, the program with an error message or forward the error to a debugger.

Checked exceptions

In Java, there is a further development of the exception " checked exception " (Eng. about: checked exception). This is an exception, in which the compiler checks that all the places where they may occur, are covered by code to catch the exception. The code to intercept can be within the same method in which the exception may occur, or in the calling methods. In the latter case, the programmer must declare the exceptions in the method signature.

The underlying idea in the design of Java was that exceptions to the application code can meaningfully respond, run as checked exception. Due to the pressure to handle the exception robust code should be achieved and lack of error handling are already discovered by the compiler. But there are still exceptions that are not Checked Exceptions. By convention applies in realizing such errors as checked exception, which is expected by the caller that he can react to it and recover a controlled program flow. This includes, for example, network, database, or other I / O error. To open a file for various reasons fail ( no rights, file does not exist ), the establishment of a network connection can fail due to the program not to be influenced reasons. Non - Checked Exceptions are provided for reporting of various kinds of program errors (for example, index errors in array indexing ). It is not recommended to let you try the application in such cases to restore a controlled program flow. The classes of the Java platform itself largely keep to this convention.

Critics argue against the Checked exceptions that they would degrade the readability of the source code and that they have many programmers because they realize this functionality it is not corresponding to the cost benefits, tempt to dodge constructs that satisfy the compiler, but hardly handle errors. Another objection is that to use due to the declaration of the exceptions in the method signatures for general use auxiliary classes or interfaces, in particular as part of design patterns, often not useful interoperable feature classes Checked Exceptions. The workaround proposed tunneled Checked exceptions, but cancel out the advantages of the checked exception.

Throwing Exceptions

An exception can be raised at any point in the program code. An object of an exception class is almost always generated and sent with the throw keyword or raise. In some programming languages ​​(eg C ) may take the Exception class, any other data type can be used.

Catching exceptions

If an exception is not caught explicitly in the program sequence, then it is caught by the runtime library. The exception is displayed as an error message; depending on the type of the exception, the application is terminated or continued. Applications without a user interface are always canceled.

Are Common Mistakes in Exception Handling

  • Exceptions are swallowed without further action. Thus, the root cause is lost.
  • Exceptions will be replaced by your own (often inaccurate ) message.

It is useful to trap exceptions to enrich additional information and to trigger again.

Examples

Object Pascal

ObjectA: = TObjectA.Create; try    try      BerechneEinkommen (name );    except      on E: Exception do      begin        / / Exception was caught and is supplemented by a descriptive note        E.Message: = 'Error in computing the income of' name # 13 # 10          E.Message; Append / / original message        raise; Trigger / / Exception modified again      end;    end; finally    FreeAndNil ( ObjectA ); / / this is done in any case end; C

Try {      function1 ();      function2 ();     ... } Catch (const std :: invalid_argument & e) {      std :: cerr << " Invalid argument: " << e.what () << std :: endl; } Catch (const std :: range_error & e) {      std :: cerr << " Out of range: " << e.what () << std :: endl; } Catch ( ... ) {      std :: cerr << " Other Exception" << std :: endl; } C #

Message Service Client client = new Client Message Service ( " httpEndpoint "); Message message = ... / / create message try {     client.AddMessage ( message); } catch ( FaultException fe) {     Console.WriteLine (fe);     client.Abort (); } catch ( Exception ce Communication ) {     Console.WriteLine (ce );     client.Abort (); } catch ( TimeoutException te) {     Console.WriteLine (te);     client.Abort (); } ISO Modula-2

MODULE example exception handling;    (* There are pre-defined and user-defined exceptions *) FROM IMPORT M2EXCEPTION M2Exception, IsM2Exception, M2Exceptions;    (* Declarations, etc. *)    IF THEN memory error      RAISE User Defined Exception;    END; BEGIN    (* Main program *) EXCEPT    (* Exception handling *) FINALLY    (* Finalize *) EXCEPT    (* If something goes wrong in the finalization *) END Example exception handling. Visual Basic. NET

' Attempts ... Try    '... The method or procedure ...    BerechneEinkommen (name) ' With the exception Catch ex AS exception    ' Give exception    MessageBox.Show ( "Error -> " & ex.Message ) ' Make definitely from finally    MessageBox.Show ( "This is still running " ) end Try Java

Try {      / / Compute ... } Catch ( OutOfMemoryError e) {      / / An error is no exception and must be taken up separately      e.printStackTrace (); } Catch ( RuntimeException e) {      / / for B. IndexOutOfBoundsException, NullPointerException, etc.      System.err.println ( "Obviously a programming error! ");      throw e; / / Leite to top next } Catch (Exception e ) {      / / Start all remaining exception from      e.printStackTrace (); } Catch ( Throwable t) {      / / This one really captures everything from      t.printStackTrace (); Finally { }      / / Exception Whether or not the lead here, definitely.      System.out.println ( "Calculation completed or aborted "); } PHP

/ / Exception handling in PHP version 5! try {        / / Compute ...        / / Error message, error code      throw new RuntimeException ( ' error', 543 );   } Catch ( RuntimeException $ e) {        / / Eg IndexOutOfBoundsException, NullPointerException, etc.      / / Important: To use the base types used here,      / / Must be installed the "SPL "        echo $ e -> getMessage ();        throw $ e; / / Leite to top next   } Catch ( Exception $ e) {        / / Start all remaining exception from and      / / Use the __ toString () - Method of Issue        echo $ e;   Finally { }        / / Since PHP 5.5      / / Code that is always executed, even      / / If an exception occurred   } Python

Try:      result = doSomething ()      if result <0:          raise the standard error   except the standard error:      print ( "catching exception" )      doSomethingElse ()   except:      print ( "exception in method doSomething " ) See also Python, Section exception handling.

Perl

Eval {      something_fatalse (...);      1; Do { } or      warn " exception: $ @"; }; # Alternatively / additionally you can also use object-oriented exception modules Web Links

  • Programming with exceptions in C O'Reilly Network article by Kyle Loudon
  • Understanding and Using Exceptions in. NET Behind the scenes of the Win32 SEH (Structured Exception Handling )
  • Errors and Exceptions The Python Tutorial ( English)
90681
de