开发中遇到的java异常(一)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/JackRen_Developer/article/details/88716006

1.NullPointerException

空指针异常,操作一个 null 对象的方法或属性时会抛出这个异常

2、OutOfMemoryError

内存异常异常,这不是程序能控制的,是指要分配的对象的内存超出了当前最大的堆内存,需要调整堆内存大小(-Xmx)以及优化程序。​

3、IOException

IO,即:input, output,我们在读写磁盘文件、网络内容的时候经常会生的一种异常,这种异常是受检查异常,需要进行手工捕获。  如文件读写会抛出 IOException:  public int read() throws IOException  public void write(int b) throws IOException

4、FileNotFoundException

文件找不到异常,如果文件不存在就会抛出这种异常。  如定义输入输出文件流,文件不存在会报错:  public FileInputStream(File file) throws FileNotFoundException  public FileOutputStream(File file) throws FileNotFoundException  FileNotFoundException 其实是 IOException 的子类,同样是受检查异常,需要进行手工捕获。

5、ClassNotFoundException

类找不到异常,Java开发中经常遇到,是不是很绝望?这是在加载类的时候抛出来的,即在类路径下不能加载指定的类。  看一个示例:  public staticClassgetExistingClass(ClassLoader classLoader, String className) {  try {  return (Class) Class.forName(className, true, classLoader);  }  catch (ClassNotFoundException e) {  return null;  }  }  预览  它是受检查异常,需要进行手工捕获。

6、ClassCastException

类转换异常,将一个不是该类的实例转换成这个类就会抛出这个异常。  如将一个数字强制转换成字符串就会报这个异常:  Object x = new Integer(0);  System.out.println((String)x);  预览  这是运行时异常,不需要手工捕获。

7、NoSuchMethodException

没有这个方法异常,一般发生在反射调用方法的时候,如:  public Method getMethod(String name, Class... parameterTypes)  throws NoSuchMethodException, SecurityException {  checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), true);  Method method = getMethod0(name, parameterTypes, true);  if (method == null) {  throw new NoSuchMethodException(getName() + . + name + argumentTypesToString(parameterTypes));  }  return method;  }  预览  它是受检查异常,需要进行手工捕获。

8、IndexOutOfBoundsException

索引越界异常,当操作一个字符串或者数组的时候经常遇到的异常。​

猜你喜欢

转载自blog.csdn.net/JackRen_Developer/article/details/88716006