1.泛型类
2.异常解决
泛型类的一般格式:
//泛型标识:可以随意写任意标识号,标识指定的泛型的类型class 类名称 <泛型标识>{//泛型变量 private 泛型标识 a; //泛型方法public 返回值 函数名 (参数类型 形参名,泛型标识 形参名){ //函数体 } }
例:
public class MyClass { public static void main(String[] args){ GenericTest<Integer> genericTest = new GenericTest<>(); genericTest.test(10,10); }}class GenericTest<T>{ int age; T a1; T a2; public void test(T a1, T a2){ this.a1 = a1; this.a2 = a2; System.out.println(a1); System.out.println(a1.equals(a2)); }}
异常类及其子类的框架:
FileReader reader = null; try { System.out.println("Hello"); reader = new FileReader("re"); }catch (FileNotFoundException e) { e.printStackTrace(); }finally { try{ reader.close(); } catch (IOException e) { e.printStackTrace(); } }
//try括号中只能增加可以关闭的对象 //实现了Closeable接口的对象,假如出现异常,系统自己关闭这个资源 try (FileReader reader1 = new FileReader("rewrwr")){ //使用对象 }catch (IOException e){ e.printStackTrace(); }
try { TException.test(); }catch (FileNotFoundException e){ e.printStackTrace(); } try { TException.test3(); }catch (ykException e){ System.out.println(e.getMessage()); }//自己设置类:class TException{ public static void test() throws FileNotFoundException,NullPointerException{ FileReader reader = new FileReader("fsf"); } //三: public static void test2()throws IllegalAccessException { if (2 > 1){ throw new IllegalAccessException(); } }}
try { TException.test3(); }catch (ykException e){ System.out.println(e.getMessage()); }class TException{ public static void test3() throws ykException { StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace(); StackTraceElement e = stackTrace[2]; String detail = e.getFileName()+"->"+e.getMethodName()+"->"+e.getLineNumber(); throw new ykException( "自己的异常类:无所作为"+detail); }}//自己设置异常class ykException extends java.lang.Exception{ //提供一个无惨构造方法 public ykException (){} //提供一个有惨构造方法 public ykException(String desc){ super(desc); }}
try{//执行的代码//一旦出现异常,系统自动为我们创立异常类,并输出 }catch(NullPointerException e){//假如需要自己解决异常,就catch }catch(IOExcepton e){ //假如有多个异常,catch的顺序是从小到大}catch(Exception e){}finally{ //资源回收:网络连接 数据库连接 文件流 I/O流// 不关也没有异常,finally都会被执行}