1.所谓异常就是程序员在编程过程中的逻辑错误,在JAVA里面有2类异常,一类是明文提示你必须要处理的异常:如
File fl = new File(""); fl.createNewFile();
如上代码,如果你不处理,编译无法通过。
还有一类是不明文提示你要处理的异常:如NullPointerException
public class test{ private String s; public static void main(String[] args){ System.out.println(s); } }
这时,代码编译能通过,但是在运行时会出现NullPointerException的情况。
2.在JAVA里如何处理异常:
在JAVA里提供了2种处理异常的办法:一种是使用try catch,另一种是使用throws,throw将异常抛出,让下一个调用者去处理。示例代码如下:
public class exception { private String str; /** * 一个异常的测试类 * * @param args */ public static void main(String[] args) { File fl = new File(""); if (fl.exists()) { System.out.println("文件存在!"); } else { //使用try catch语句处理异常 try { fl.createNewFile(); } catch (Exception ef) { ef.printStackTrace(); } finally { return; } } } }
public class exception { private String str; /** * 一个异常的测试类 * * @param args */ public static void main(String[] args) { File fl = new File(""); exception ex = new exception(); try { ex.testex(); } catch (Exception def) { def.printStackTrace(); } } // ** // * 测试异常的抛出方法 // *// public void testex() throws Exception { if (str.equals("123")) { System.out.println("Don't have NullPointException"); } else { System.out.println("NullPointException"); } } }
以上代码中的exception类的对象在调用抛出异常的testex()方法时必须处理异常,否则编译无法通过。
3.如何自定义异常
首先创建一个自定义异常类,让它继承Exception类,然后在具体使用时用throws关键字抛出异常,代码如下:
package ExceptionT; public class DefException extends Exception{ /** * 重写构造函数 */ public DefException(String message){ super(message); } }
package ExceptionT; import java.io.File; public class exception { private String str; /** * 一个异常的测试类 * * @param args */ public static void main(String[] args) { exception ex = new exception(); try { ex.testthrow(); } catch (DefException def) { //打印出异常信息 System.out.println(def.toString()); } } /** * 测试异常的抛出方法 */ public void testex() throws Exception { if (str.equals("123")) { System.out.println("Don't have NullPointException"); } else { System.out.println("NullPointException"); } } /** * 测试异常的抛出方法 */ public void testthrow() throws Exception { try { this.testex(); } catch (Exception ef) { throw new DefException("自定义的异常"); } } }
代码运行的结果是 ExceptionT.DefException: 自定义的异常。
那么如何将一个异常定义成像NullPointerException这样不明文提示程序员要处理的异常呢,经过一番询问,得知只要让自定义的异常去继承RuntimeException即可.代码如下:
package ExceptionT; public class DefException extends RuntimeException{ /** * 重写构造函数 */ public DefException(String message){ super(message); } }
4.与异常处理相关的一些关键字。
try catch finally
throws
throw
上面关于JAVA异常机制的总结还是很有限的,如果里面有些不正确的内容欢迎大家指正,帮助我进步。