简体   繁体   中英

2 approaches in exception handling

In Java Language Specification 8 (JLS8) >>> Chapter 11: Exceptions ( here ), I saw that they are 2 two approaches for exception handling:

Some programming languages and their implementations react to such errors by peremptorily terminating the program ; other programming languages allow an implementation to react in an arbitrary or unpredictable way . Neither of these approaches is compatible with the design goals of the Java SE platform: to provide portability and robustness.

1st approach: peremptorily terminating the program 2nd approach: arbitrary or un-predictable way

But, I cannot distinguish clearly these 2 ways and what's the language will use they (what's language use 1st approach? what's language use 2nd approach?). Please help me to clarify this issue and give me an example to demonstrate

Moreover, the "portability" of Java, in this case, means what?

Not sure about programming languages that peremptorily terminate the program , but it could be that early versions of Pascal handled the problem this way (reasoning that it's better to terminate the program than to introduce arbitrary errors into the result).

To react in an arbitrary or unpredictably way : consider what happens if a program written in C accesses an array outside of it's bounds: you get a buffer overflow. Buffer overflows are the base for many security problems (search for "buffer overflow attack").


Consider this simple C function:

int test(int arg) {
    int x;
    int arr[8];
    int y;
    x = 0; y = 0;
    arr[8] = 99;
    printf("%d %d\n", x, y);
    return x+y;
}

Executing this simple function could:

  • print out "0 0"
  • print out "99 0"
  • print out "0 99"
  • crash the program
  • format your hard disk

A similar method written in Java will always throw an ArrayIndexOutOfBoundsException

Peremptorily terminating the program = throwing a NullPointerException you can't catch (not that you ever should).

Allowing an implementation to react in an arbitrary or unpredictable way = not throwing a NullPointerException at all. There are languages that do just that (think sending a message to a nil object in Objective-C).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM