Skip to content

Instantly share code, notes, and snippets.

@zlargon
Last active December 21, 2016 17:51
Show Gist options
  • Save zlargon/b5eebf0c010f4a2159b2abf4c3ab72ef to your computer and use it in GitHub Desktop.
Save zlargon/b5eebf0c010f4a2159b2abf4c3ab72ef to your computer and use it in GitHub Desktop.
An example of exception in C and Java
#include <stdio.h>
// int add (int a, int b) {
// return a + b;
// }
/*
* @param {int} sum
* @param {int} a
* @param {int} b
* @return {int} 0 success
* -1 null pointer
* -2 overflow
* -3 underflow
*/
int add (int * sum, int a, int b) {
if (sum == NULL) return -1; // Null Pointer
*sum = a + b;
if (a > 0 && b > 0 && *sum <= 0) return -2; // Overflow
if (a < 0 && b < 0 && *sum >= 0) return -3; // Underflow
return 0; // success
}
int main () {
int sum, a = -2147483648, b = -1;
int ret = add(&sum, a, b); // Underflow
if (ret == 0) {
printf("sum = %d\n", sum);
} else {
// error handle
switch (ret) {
case -1:
printf("sum should not be NULL\n");
break;
case -2:
printf("Overflow: %d, %d\n", a, b);
break;
case -3:
printf("Underflow: %d, %d\n", a, b); // "Underflow: -2147483648, -1"
break;
default:
printf("Unknown Error Code: %d\n", ret);
}
}
}
public class Example {
// static int add (int a, int b) {
// return a + b;
// }
static int add (int a, int b) {
int sum = a + b;
// Overflow
if (a > 0 && b > 0 && sum <= 0) {
throw new RuntimeException("Overflow: " + a + ", " + b);
}
// Underflow
if (a < 0 && b < 0 && sum >= 0) {
throw new RuntimeException("Underflow: " + a + ", " + b);
}
return a + b;
}
public static void main(String [] args) {
try {
int result = add(Integer.MAX_VALUE, 1); // Overflow
System.out.println(result);
} catch (Exception e) {
System.out.println(e.getMessage()); // "Overflow: 2147483647, 1"
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment