我们在编写程序的时候往往都会抛出不可预期的异常,如c中常见的内存不足异常,java中的类型转换异常。因此,我们处理异常往往会有以下的代码形式:
java语言:
try {
URL url = new URL("cym.so");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
### c语言:
if( p == NULL)
{
printf( "ERR: The pointer is NULL\n" );
}
用陈浩老师的话讲,上面的属于学生时代的编程,很不利于维护和管理。
对于出错信息和提示信息,应该统一处理。而不是写成“硬编码”。
我总结了java和c两种语言的异常处理的通用方法,发现在项目中运用起来作用还是不小的。
JAVA:
1.建立一个继承Exception的公用的异常类,声明一些常用的异常。
public class CustomException extends Exception{
/** NO_ERROR 8*/
public static final int NO_ERROR =0;
/** UNKNOW_ERROR */
public static final int UNKNOWN_ERROR = 1;
/** IO_ERROR */
public static final int NET_IO_ERROR = 2;
/** INVALID_LITERAL_LENGTH */
public static final int INVALID_LITERAL_LENGTH = 3;
/** SERVER_CLOSE_CONNECTION */
public static final int SERVER_CLOSE_CONNECTION = 4;
/** JSON_TRANFORM_FAILED */
public static final int JSON_TRANFORM_FAILED = 5;
public static final int TRANSITION_EXCEPTION = 6;
}
2. 为公用的异常类提供几个常用的构造函数:
/**
*
* @param errorType the type of exception
* @param errorMsg the msg of exception
* @param errorData the extra data of exception
*/
public CustomException (int errorType, String errorMsg, Object errorData){
super(errorMsg);
this.errorType = errorType;
this.errorData = errorData;
}
/**
* @param type the type of exception.
*/
public CustomException(int type) {
this(type, "", null);
}
/**
* @param type the type of exception.
* @param message the message of exception.
* @param throwable the throwable object.
*/
public CustomException(int type, String message, Throwable throwable) {
super(message, throwable);
errorType = type;
errorData = null;
}
/**
* @param message the message of exception.
* @param throwable the throwable object.
*/
public CustomException(String message, Throwable throwable) {
this(UNKNOWN_ERROR, message, throwable);
}
3. 有异常发生时的调用方法
try {
URL url = new URL("cym.so");
} catch (MalformedURLException e) {
throw new CustomException(CustomException.TRANSITION_EXCEPTION,"url转换错误",e);
}
4.执行效果
C语言
1.声明出错代码:
# define ERR_NO_ERROR 0 /* NO ERROR */
# define UNKNOWN_ERROR 1 /* UNKNOWN ERROR */
# define MEMEROY_IS_NOT_ENOUGH 2 /* MEMEROY IS NOT ENOUGH */
# define PERMISSION_DENIED 3 /* PERMISSION DENIED */
# define BAD_CONFIGURATION_FILE_FORMAT 4 /* BAD CONFIGURATION FILE FORMAT */
# define TIME_OUT 5 /* TIME OUT */
2.声明出错信息
const char* errmsg[] = {
"NO ERROR",
"UNKNOWN ERROR",
"MEMEROY IS NOT ENOUGH",
"PERMISSION DENIED",
"BAD CONFIGURATION FILE FORMAT",
"TIME OUT"
};
3.声明出错代码全局变量
long errorno = 0;
4.打印出错信息函数
void perror(char* info)
{
if( info )
{
printf("%s: %s\n", info, errmsg[errorno]);
return;
}
printf("Error: %s\n", errmsg[errorno]);
}
5.调用方式
char *p = (char *)malloc(sizeof(char *));
if(!p)
{
errorno = 2;
perror("main()");
}
free(p);