Advertisement
Guest User

Untitled

a guest
Oct 22nd, 2019
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 6.13 KB | None | 0 0
  1. # CSCE 155H - Computer Science I - Honors
  2. ## Error Handling
  3. ### Fall 2019
  4.  
  5. * Errors can either be completely unexpected or anticipated but not normal
  6. * Some errors are, by nature, *fatal* errors: when encountered, the program *should* die
  7. * Ie you cannot *recover* from the error
  8. * In general you can take one of two strategies for *handling errors*
  9. 1. Defensive Programming: "look before you leap"
  10. * You write code to detect potentially bad operations before they occur
  11. * If they would occur, you don't do them
  12. * Instead, you communicate the error somehow to the calling function or other code.
  13. * It is that other code's responsibility to decide how to handle the error.
  14. 2. Exceptions
  15. * "Modern" programming languages support exceptions
  16. * Go ahead and do a dangerous operations: leap before you look
  17. * You can then write code to "try" these dangerous exceptions, and if they result in an error they can be "caught"
  18.  
  19. ## Defensive Programming in C
  20.  
  21. * In C, you design functions such that the actual return values are communicated using pass-by-reference variables
  22. * This frees up the return value to be an error code: an integer that indicates the *type* of error encountered
  23. * In general: zero indicates no error
  24. * In general: don't use magic numbers (mysterious numbers that have no apparent meaning): it makes your code unreadable and unmaintainable
  25.  
  26. * Example: how does standard C handle errors?
  27. * The POSIX standard actually only defines 3 types of errors:
  28. * `EDOM`: indicate an error in the *domain* of a function; an error in the input of a function
  29. * Example: `sqrt(-1)` results in an `EDOM` error
  30. * `ERANGE`: indicates an error in the *range* of a function; an error in the output of a function
  31. * Example: `log(0)`
  32. * `EILSEQ`: illegal byte sequence
  33. * 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)
  34. * Demonstration: errorDemo.c
  35.  
  36. * In C you can define error flag values with ether preprocessor directives or enumerated types
  37.  
  38. ### Enumerated Type
  39.  
  40. * Many pieces of data may have a small and limited number of possible values
  41. * Example: day of the week, months, error codes
  42. * In C you can define an enumerated type and give predefined, human-readable values to them
  43.  
  44. ```c
  45. typedef enum {
  46. SUNDAY,
  47. MONDAY,
  48. TUESDAY,
  49. WEDNESDAY,
  50. THURSDAY,
  51. FRIDAY,
  52. SATURDAY,
  53. } DayOfWeek;
  54. ```
  55.  
  56. Syntax and Style notes:
  57. * You use `typedef enum` with curly brackets and the "name" of the type at the end with a semicolon
  58. * The name of an enumerated type will be `UpperCamelCased`
  59. * Each element will have an `UPPER_UNDERSCORE_CASE`
  60. * You list one element per line
  61. * The last comma is optional but recommended
  62.  
  63. * Later on in the code, you can use your enumerated type just like an other built-in type
  64.  
  65. ```c
  66. DayOfWeek today = TUEDSAY;
  67. DayOfWeek tomorrow = WEDNESDAY;
  68.  
  69. if(today == FRIDAY) {
  70. printf("TGIF!\n");
  71. }
  72. ```
  73.  
  74. * Careful: in C, enumerated types are integers under the hood
  75. * Starting at zero, each element is given an integer value
  76. * Example: `SUNDAY` has a value of 0, `MONDAY` has a value of 1, etc. `SATURDAY` has a value of 6
  77. * You can (but should not) abuse enumerated types:
  78.  
  79. ```c
  80. DayOfWeek today = SATURDAY;
  81. today++; //what is today now?: 7, an invalid value
  82. today = 1234;
  83.  
  84. //you can, if you are careful:
  85. today = (today + 1) % 7;
  86. ```
  87.  
  88. ## Error Handling in Java: Exceptions
  89.  
  90. * Java uses exceptions instead of defensive programming
  91. * An *exception* is an interruption of the normal inear flow of control
  92. * 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
  93. * Advantages:
  94. * With error codes there is no *semantic* meaning to the code: even if you don't use magic numbers, it is just an integer
  95. * With exceptions you *do* have semantic meanings:
  96. `NullPointerException` and `InputMismatchException` are completely different *types* errors
  97. * Often defensive programming leads to large, nested and separate error handling code and "GOTO FAIL" style errors
  98.  
  99. ### Exceptions in Java
  100.  
  101. * In Java all exceptions are a "subclass" of `Throwable` objects
  102. * There are two main types of `Throwable`s
  103. * `Error`: mainly used by the JVM and is always fatal
  104. * `Exception`: is what you *do* use in a program
  105. * Two general types of exceptions:
  106. * `Exception`: a "checked" exception: a type of exception that you *must* (are forced to) surround with a `try-catch` block
  107. * `RuntimeException`: an "unchecked" exception: you can optionally surround this with a try-catch block
  108.  
  109. ## Syntax
  110.  
  111. * IN general, you surround potentially dangerous code with a `try-catch` block
  112. * You can `catch` multiple different types of exceptions and handle them differently
  113. * Similar to an if-else-if statement: the first one matched is the one that gets executed
  114. * Demo code:
  115.  
  116. ```java
  117. import java.io.File;
  118. import java.io.FileNotFoundException;
  119. import java.util.InputMismatchException;
  120. import java.util.Scanner;
  121.  
  122. public class Demo {
  123.  
  124. public static void main(String args[]) {
  125. int value = -1;
  126. try {
  127. // potentially dangerous/error code here
  128. // try to open a file an dprocess it
  129. File f = new File("data/myData.txt");
  130. Scanner s;
  131. s = new Scanner(f);
  132. value = s.nextInt();
  133. // file could maybe not exist
  134. // may not have permissions
  135. // file contents may not be an integer
  136. } catch (FileNotFoundException fnfe) {
  137. //catch and release: we are forced to catch
  138. // a checked exception, but we'll rethrow it as
  139. // an unchecked excpetion
  140. throw new RuntimeException(fnfe);
  141. } catch (InputMismatchException ime) {
  142. System.out.println("Warning: no value found, using default");
  143. value = 10;
  144. } catch (NullPointerException npe) {
  145. //do something else, or nothing!
  146. } catch (Exception e) {
  147. e.printStackTrace();
  148. }
  149. System.out.println(value);
  150.  
  151. }
  152.  
  153. }
  154. ```
  155.  
  156. * You can also create and throw your own custom exceptions
  157. * You can create a new type of exception by creating a new class that `extends RuntimeException`
  158. * Example code:
  159.  
  160. TODO
  161.  
  162. * With try-catch blocks you can also have `finally` block
  163. * The `finally` block will execute regardless of whether or not an exception occurred
  164. * Example: file I/O
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement