Upozornenie: Prezeranie týchto stránok je určené len pre návštevníkov nad 18 rokov!
Zásady ochrany osobných údajov.
Používaním tohto webu súhlasíte s uchovávaním cookies, ktoré slúžia na poskytovanie služieb, nastavenie reklám a analýzu návštevnosti. OK, súhlasím









A | B | C | D | E | F | G | H | CH | I | J | K | L | M | N | O | P | Q | R | S | T | U | V | W | X | Y | Z | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9

IOError
 

Exception handling syntax is the set of keywords and/or structures provided by a computer programming language to allow exception handling, which separates the handling of errors that arise during a program's operation from its ordinary processes. Syntax for exception handling varies between programming languages, partly to cover semantic differences but largely to fit into each language's overall syntactic structure. Some languages do not call the relevant concept "exception handling"; others may not have direct facilities for it, but can still provide means to implement it.

Most commonly, error handling uses a try... block, and errors are created via a throw statement, but there is significant variation in naming and syntax.

Catalogue of exception handling syntaxes

Ada

Exception declarations
Some_Error : exception;
Raising exceptions
raise Some_Error;

raise Some_Error with "Out of memory"; -- specific diagnostic message
Exception handling and propagation
with Ada.Exceptions, Ada.Text_IO;

procedure Foo is
  Some_Error : exception;
begin
  Do_Something_Interesting;
exception -- Start of exception handlers
  when Constraint_Error =>
    ... -- Handle constraint error
  when Storage_Error =>
    -- Propagate Storage_Error as a different exception with a useful message
    raise Some_Error with "Out of memory";
  when Error : others => 
    -- Handle all others
    Ada.Text_IO.Put("Exception: ");
    Ada.Text_IO.Put_Line(Ada.Exceptions.Exception_Name(Error));
    Ada.Text_IO.Put_Line(Ada.Exceptions.Exception_Message(Error));
end Foo;

Assembly language

Most assembly languages will have a macro instruction or an interrupt address available for the particular system to intercept events such as illegal op codes, program check, data errors, overflow, divide by zero, and other such. IBM and Univac mainframes had the STXIT macro. Digital Equipment Corporation RT11 systems had trap vectors for program errors, i/o interrupts, and such. DOS has certain interrupt addresses. Microsoft Windows has specific module calls to trap program errors.

Bash

#!/usr/bin/env bash
#set -e provides another error mechanism
print_error(){
	echo "there was an error"
}
trap print_error exit #list signals to trap
tempfile=`mktemp`
trap "rm $tempfile" exit
./other.sh || echo warning: other failed
echo oops)
echo never printed

One can set a trap for multiple errors, responding to any signal with syntax like:

trap 'echo Error at line ${LINENO}' ERR

BASIC

An On Error goto/gosub structure is used in BASIC and is quite different from modern exception handling; in BASIC there is only one global handler whereas in modern exception handling, exception handlers are stacked.

ON ERROR GOTO handler
OPEN "Somefile.txt" FOR INPUT AS #1
CLOSE #1
PRINT "File opened successfully"
END

handler:
PRINT "File does not exist"
END  ' RESUME may be used instead which returns control to original position.

C

C does not provide direct support to exception handling: it is the programmer's responsibility to prevent errors in the first place and test return values from the functions.

In any case, a possible way to implement exception handling in standard C is to use setjmp/longjmp functions:

#include <setjmp.h>
#include <stdio.h>
#include <stdlib.h>

enum { SOME_EXCEPTION = 1 } exception;
jmp_buf state;

int main(void)
{
  if (!setjmp(state))                      // try
  {
    if (/* something happened */)
    {
      exception = SOME_EXCEPTION;
      longjmp(state, 0);                  // throw SOME_EXCEPTION
    }
  } 
  else switch(exception)
  {             
    case SOME_EXCEPTION:                  // catch SOME_EXCEPTION
      puts("SOME_EXCEPTION caught");
      break;
    default:                              // catch ...
      puts("Some strange exception");
  }
  return EXIT_SUCCESS;
}

Microsoft-specific

Two types exist:

  • Structured Exception Handling (SEH)
  • Vectored Exception Handling (VEH, introduced in Windows XP)

Example of SEH in C programming language:

int filterExpression (EXCEPTION_POINTERS* ep) {
   ep->ContextRecord->Eip += 8; // divide instruction may be encoded from 2 to 8 bytes
   return EXCEPTION_CONTINUE_EXECUTION;
}
int main(void) {
   static int zero;
   __try {
       zero = 1/zero;
       __asm {
         nop
         nop
         nop
         nop
         nop
         nop
         nop
       }
       printf ("Past the exception.\n");
   } __except (filterExpression (GetExceptionInformation())) {
       printf ("Handler called.\n");
   }
   return 0;
}

C#

A try block must have at least one catch or finally clause and at most one finally clause.

public static void Main()
{
    try
    {
        // Code that could throw an exception.
    }
    catch (HttpException ex)
    {
        // Handles a HttpException. The exception object is stored in "ex".
    }
    catch (Exception)
    {
        // Handles any CLR exception that is not a HttpException.
        // Since the exception has not been given an identifier, it cannot be referenced.
    }
    catch
    {
        // Handles anything that might be thrown, including non-CLR exceptions.
    }
    finally
    {
        // Always run when leaving the try block (including catch clauses), regardless of whether any exceptions were thrown or whether they were handled.
        // Often used to clean up and close resources such a file handles.
        // May not be run when Environment.FailFast() is called and in other system-wide exceptional conditions (e.g. power loss), or when the process crashes due to an exception in another thread.
    }
}

C++

#include <exception>
int main() {
   try {
       // do something (might throw an exception)
   }
   catch (const std::exception& e) {
        // handle exception e
   }
   catch (...) {
        // catches all exceptions, not already caught by a catch block before
        // can be used to catch exception of unknown or irrelevant type
   }
}

In C++, a resource acquisition is initialization technique can be used to clean up resources in exceptional situations. C++ intentionally does not support finally.[1] The outer braces for the method are optional.

ColdFusion Markup Language (CFML)

Script syntax

<cfscript>
try {
	//throw CF9+
	throw(type="TypeOfException", message="Oops", detail="xyz");
	// alternate throw syntax:
	throw "Oops"; // this equivalent to the "message" value in the above example
} catch (any e) {
	writeOutput("Error: " & e.message);
	rethrow; //CF9+
} finally { //CF9+
	writeOutput("I run even if no error");
}
</cfscript>

Adobe ColdFusion documentation[2]

Tag syntax

<cftry> 
    code that may cause an exception 
    <cfcatch ...> 
        <cftry> 
            First level of exception handling code 
            <cfcatch ...> 
                Second level of exception handling code 
            </cfcatch>
            <cffinally> 
                    final code    
             </cffinally> 
        </cftry> 
    </cfcatch> 
</cftry>

Adobe ColdFusion documentation[3]

Railo-Lucee specific syntax

Added to the standard syntax above, CFML dialects of Railo and Lucee allow a retry statement.[4]

This statement returns processing to the start of the prior try block.

CFScript example:

try {
	// code which could result in an exception

} catch (any e){
	retry;
}

Tag-syntax example:

<cftry>

	<!--- code which could result in an exception --->

	<cfcatch>
		<cfretry>
	</cfcatch>
</cftry>

D

import std.stdio; // for writefln()
int main() {
  try {
      // do something that might throw an exception
  }
  catch (FooException e) {
       // handle exceptions of type FooException
  }
  catch (Object o) {
       // handle any other exceptions
       writefln("Unhandled exception: ", o);
       return 1;
  }
  return 0;
}

In D, a finally clause or the resource acquisition is initialization technique can be used to clean up resources in exceptional situations.

Delphi

Exception declarations
type ECustom = class(Exception) // Exceptions are children of the class Exception.
  private
    FCustomData: SomeType;      // Exceptions may have custom extensions.
  public
    constructor CreateCustom(Data: SomeType); // Needs an implementation
    property CustomData: SomeType read FCustomData;
  end;
Raising exceptions
raise Exception.Create('Message');

raise Exception.CreateFmt('Message with values: %d, %d',); // See SysUtils.Format() for parameters.

raise ECustom.CreateCustom(X);
Exception handling and propagation[5]
try // For finally.
  try // For except.
Zdroj:https://en.wikipedia.org?pojem=IOError
>Text je dostupný pod licencí Creative Commons Uveďte autora – Zachovejte licenci, případně za dalších podmínek. Podrobnosti naleznete na stránce Podmínky užití.

čítajte viac o IOError





Text je dostupný za podmienok Creative Commons Attribution/Share-Alike License 3.0 Unported; prípadne za ďalších podmienok.
Podrobnejšie informácie nájdete na stránke Podmienky použitia.