异常处理机制
一、异常概念
异常是程序在编译或运行过程出现的例外,这些例外在有的可以避免有的却无法避免
二、异常分类
检查异常也称为编译期异常:
- 不可避免 必须进行异常处理,要不编译器报错
- Exception以及它的子类(除去RuntimeException)
未检查异常也称为运行时异常:
- 可以避免 不需要必须处理
- RuntimeException以及它的子类
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-CcsuFAwN-1627285642364)(C:/Users/lenovo/AppData/Roaming/Typora/typora-user-images/image-20210726140833377.png)]
常见异常:
数组下标越界异常:ArrayIndexOutOfBoundsException
字符串下标越界异常:StringIndexOutOfBoundsException
解析异常:ParseException
数字格式化异常:NumberFormatException
输入不匹配异常:InputMismatchException
文件找不到异常:FileNotFoundException
算术异常:ArithmeticException
空指针异常:NullPointerException
没有这样的元素异常:NoSuchElementException
类型转换异常:ClassCastException
栈溢出异常:StackOverfflowError
异常:
AclNotFoundException, ActivationException, AlreadyBoundException, ApplicationException, AWTException, BackingStoreException, BadAttributeValueExpException, BadBinaryOpValueExpException, BadLocationException, BadStringOperationException, BrokenBarrierException, CertificateException, ClassNotFoundException, CloneNotSupportedException, DataFormatException, DatatypeConfigurationException, DestroyFailedException, ExecutionException, ExpandVetoException, FontFormatException, GeneralSecurityException, GSSException, IllegalAccessException, IllegalClassFormatException, InstantiationException, InterruptedException, IntrospectionException, InvalidApplicationException, InvalidMidiDataException, InvalidPreferencesFormatException, InvalidTargetObjectTypeException, InvocationTargetException, IOException, JAXBException, JMException, KeySelectorException, LastOwnerException, LineUnavailableException, MarshalException, MidiUnavailableException, MimeTypeParseException, MimeTypeParseException, NamingException, NoninvertibleTransformException, NoSuchFieldException, NoSuchMethodException, NotBoundException, NotOwnerException, ParseException, ParserConfigurationException, PrinterException, PrintException, PrivilegedActionException, PropertyVetoException, RefreshFailedException, RemarshalException, RuntimeException, SAXException, ScriptException, ServerNotActiveException, SOAPException, SQLException, TimeoutException, TooManyListenersException, TransformerException, TransformException, UnmodifiableClassException, UnsupportedAudioFileException, UnsupportedCallbackException, UnsupportedFlavorException, UnsupportedLookAndFeelException, URIReferenceException, URISyntaxException, UserException, XAException, XMLParseException, XMLSignatureException, XMLStreamException, XPathException
三、异常处理方式
Java编译期异常必须要进行处理,否则Java源文件在编译时编译器会提示错误,且源文件无法成功编译
Java编译期异常的处理方式有两种
- 使用try、catch、finally关键字捕获异常
- 使用throws关键字声明抛出异常
使用try、catch、finally捕获异常:
try{
//可能会出现异常的代码
//如果异常,内部任何程序都不会执行、
return;
}catch(ParseException e){
//捕获执行的代码
}finally{
//不管是否发生异常都要执行的代码
return;
}
先执行finally里的,后执行try里的。
实例演示: