Exception是Java程序中经常遇到的问题。我认为每个Java程序员都讨厌异常。异常就是BUG,定位异常要花很多时间。什么是异常及其分类请看这篇文章:一张图搞清楚Java异常机制。今天,栈长将列出Java中经常遇到的Top10异常,排名不分先后。1.NullPointerException空指针异常,在操作空对象的方法或属性时会抛出该异常。2、OutOfMemoryError异常。这不受程序控制。意思是要分配的对象的内存超过了当前的最大堆内存。需要调整堆内存大小(-Xmx),优化程序。3.IOExceptionIO,即:输入,输出,我们读写磁盘文件和网络内容时经常出现的异常。这个异常是checkedexception,需要手动捕获。如文件读写会抛出IOException:publicintread()throwsIOExceptionpublicvoidwrite(intb)throwsIOException4、FileNotFoundExceptionfilenotfound异常,如果文件不存在会抛出此异常。如果定义了输入输出文件流,如果文件不存在会报错:publicFileInputStream(Filefile)throwsFileNotFoundExceptionpublicFileOutputStream(Filefile)throwsFileNotFoundExceptionFileNotFoundException其实是IOException的子类,也是checked,需要手动捕获。5、ClassNotFoundException类找不到,在Java开发中经常遇到。你绝望了吗?这是加载类时抛出的,即类路径下无法加载指定的类。看一个例子:publicstaticClassgetExistingClass(ClassLoaderclassLoader,StringclassName){try{return(Class)Class.forName(className,true,classLoader);}catch(ClassNotFoundExceptione){returnull;}}it是checkedexception,需要手动捕获。6.ClassCastException类转换异常,将不属于该类的实例转换为该类会抛出该异常。如果强制将数字转换为字符串,会报这个异常:Objectx=newInteger(0);System.out.println((String)x);这是一个运行时异常,不需要手动捕获。7.NoSuchMethodException没有这个方法异常。一般在反射调用方法时出现,如:publicMethodgetMethod(Stringname,Class>...parameterTypes)throwsNoSuchMethodException,SecurityException{checkMemberAccess(Member.PUBLIC,Reflection.getCallerClass(),true);Methodmethod=getMethod0(name,parameterTypes,true);if(method==null){thrownewNoSuchMethodException(getName()+"."+name+argumentTypesToString(parameterTypes));}returnmethod;}是checkedexception,需要手工捕获。8.IndexOutOfBoundsException索引越界异常,在操作字符串或数组时经常遇到的异常。如图所示,是运行时异常,不需要手动捕获。9.ArithmeticException算术异常,在数字的算术运算过程中出现的异常,比如一个数除以0就会报这个错误。双倍=3/0;虽然这个异常是运行时异常,但是你可以手动捕获并抛出一个自定义的异常,比如:;returnstamp;}catch(ArithmeticExceptionex){thrownewIllegalArgumentException(ex);}}10.SQLException是操作数据库时出现的异常。获取连接如下:publicConnectiongetConnection()throwsSQLException{if(getUser()==null){returnDriverManager.getConnection(url);}else{returnDriverManager.getConnection(url,getUser(),getPassword());}}或者它是时候获取下一条记录了:booleannext()throwsSQLException;是checkedexception,需要手动捕获。