Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # CSCE 155H - Computer Science I - Honors
- ## Error Handling
- ### Fall 2019
- * Errors can either be completely unexpected or anticipated but not normal
- * Some errors are, by nature, *fatal* errors: when encountered, the program *should* die
- * Ie you cannot *recover* from the error
- * In general you can take one of two strategies for *handling errors*
- 1. Defensive Programming: "look before you leap"
- * You write code to detect potentially bad operations before they occur
- * If they would occur, you don't do them
- * Instead, you communicate the error somehow to the calling function or other code.
- * It is that other code's responsibility to decide how to handle the error.
- 2. Exceptions
- * "Modern" programming languages support exceptions
- * Go ahead and do a dangerous operations: leap before you look
- * You can then write code to "try" these dangerous exceptions, and if they result in an error they can be "caught"
- ## Defensive Programming in C
- * In C, you design functions such that the actual return values are communicated using pass-by-reference variables
- * This frees up the return value to be an error code: an integer that indicates the *type* of error encountered
- * In general: zero indicates no error
- * In general: don't use magic numbers (mysterious numbers that have no apparent meaning): it makes your code unreadable and unmaintainable
- * Example: how does standard C handle errors?
- * The POSIX standard actually only defines 3 types of errors:
- * `EDOM`: indicate an error in the *domain* of a function; an error in the input of a function
- * Example: `sqrt(-1)` results in an `EDOM` error
- * `ERANGE`: indicates an error in the *range* of a function; an error in the output of a function
- * Example: `log(0)`
- * `EILSEQ`: illegal byte sequence
- * The C libraries "raise" these errors using the errno.h library: defines all of the errors and a global integer variable named `errno` (error number)
- * Demonstration: errorDemo.c
- * In C you can define error flag values with ether preprocessor directives or enumerated types
- ### Enumerated Type
- * Many pieces of data may have a small and limited number of possible values
- * Example: day of the week, months, error codes
- * In C you can define an enumerated type and give predefined, human-readable values to them
- ```c
- typedef enum {
- SUNDAY,
- MONDAY,
- TUESDAY,
- WEDNESDAY,
- THURSDAY,
- FRIDAY,
- SATURDAY,
- } DayOfWeek;
- ```
- Syntax and Style notes:
- * You use `typedef enum` with curly brackets and the "name" of the type at the end with a semicolon
- * The name of an enumerated type will be `UpperCamelCased`
- * Each element will have an `UPPER_UNDERSCORE_CASE`
- * You list one element per line
- * The last comma is optional but recommended
- * Later on in the code, you can use your enumerated type just like an other built-in type
- ```c
- DayOfWeek today = TUEDSAY;
- DayOfWeek tomorrow = WEDNESDAY;
- if(today == FRIDAY) {
- printf("TGIF!\n");
- }
- ```
- * Careful: in C, enumerated types are integers under the hood
- * Starting at zero, each element is given an integer value
- * Example: `SUNDAY` has a value of 0, `MONDAY` has a value of 1, etc. `SATURDAY` has a value of 6
- * You can (but should not) abuse enumerated types:
- ```c
- DayOfWeek today = SATURDAY;
- today++; //what is today now?: 7, an invalid value
- today = 1234;
- //you can, if you are careful:
- today = (today + 1) % 7;
- ```
- ## Error Handling in Java: Exceptions
- * Java uses exceptions instead of defensive programming
- * An *exception* is an interruption of the normal inear flow of control
- * Philosophy: go ahead and leap before you look; `try` some potentially dangerous code, we'll `catch` you if you fall, then you can handle the error
- * Advantages:
- * With error codes there is no *semantic* meaning to the code: even if you don't use magic numbers, it is just an integer
- * With exceptions you *do* have semantic meanings:
- `NullPointerException` and `InputMismatchException` are completely different *types* errors
- * Often defensive programming leads to large, nested and separate error handling code and "GOTO FAIL" style errors
- ### Exceptions in Java
- * In Java all exceptions are a "subclass" of `Throwable` objects
- * There are two main types of `Throwable`s
- * `Error`: mainly used by the JVM and is always fatal
- * `Exception`: is what you *do* use in a program
- * Two general types of exceptions:
- * `Exception`: a "checked" exception: a type of exception that you *must* (are forced to) surround with a `try-catch` block
- * `RuntimeException`: an "unchecked" exception: you can optionally surround this with a try-catch block
- ## Syntax
- * IN general, you surround potentially dangerous code with a `try-catch` block
- * You can `catch` multiple different types of exceptions and handle them differently
- * Similar to an if-else-if statement: the first one matched is the one that gets executed
- * Demo code:
- ```java
- import java.io.File;
- import java.io.FileNotFoundException;
- import java.util.InputMismatchException;
- import java.util.Scanner;
- public class Demo {
- public static void main(String args[]) {
- int value = -1;
- try {
- // potentially dangerous/error code here
- // try to open a file an dprocess it
- File f = new File("data/myData.txt");
- Scanner s;
- s = new Scanner(f);
- value = s.nextInt();
- // file could maybe not exist
- // may not have permissions
- // file contents may not be an integer
- } catch (FileNotFoundException fnfe) {
- //catch and release: we are forced to catch
- // a checked exception, but we'll rethrow it as
- // an unchecked excpetion
- throw new RuntimeException(fnfe);
- } catch (InputMismatchException ime) {
- System.out.println("Warning: no value found, using default");
- value = 10;
- } catch (NullPointerException npe) {
- //do something else, or nothing!
- } catch (Exception e) {
- e.printStackTrace();
- }
- System.out.println(value);
- }
- }
- ```
- * You can also create and throw your own custom exceptions
- * You can create a new type of exception by creating a new class that `extends RuntimeException`
- * Example code:
- TODO
- * With try-catch blocks you can also have `finally` block
- * The `finally` block will execute regardless of whether or not an exception occurred
- * Example: file I/O
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement