java异常处理及自定义异常的使用
Posted motivated_Dou
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java异常处理及自定义异常的使用相关的知识,希望对你有一定的参考价值。
1. 异常介绍
异常机制可以提高程序的健壮性和容错性。
Throwable:Throwable是java语言所有错误或异常的超类。 有两个子类Error和Exception。
1.1 编译期异常
编译期异常必须处理,否则编译无法通过。
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, SAXException, ScriptException, ServerNotActiveException, SOAPException, SQLException, TimeoutException, TooManyListenersException, TransformerException, TransformException, UnmodifiableClassException, UnsupportedAudioFileException, UnsupportedCallbackException, UnsupportedFlavorException, UnsupportedLookAndFeelException, URIReferenceException, URISyntaxException, UserException, XAException, XMLParseException, XMLSignatureException, XMLStreamException, XPathException
1.2 运行期异常(RuntimeException)
AnnotationTypeMismatchException, ArithmeticException, ArrayStoreException, BufferOverflowException, BufferUnderflowException, CannotRedoException, CannotUndoException, ClassCastException, CMMException, ConcurrentModificationException, DOMException, EmptyStackException, EnumConstantNotPresentException, EventException, IllegalArgumentException, IllegalMonitorStateException, IllegalPathStateException, IllegalStateException, ImagingOpException, IncompleteAnnotationException, IndexOutOfBoundsException, JMRuntimeException, LSException, MalformedParameterizedTypeException, MirroredTypeException, MirroredTypesException, MissingResourceException, NegativeArraySizeException, NoSuchElementException, NoSuchMechanismException, NullPointerException, ProfileDataException, ProviderException, RasterFormatException, RejectedExecutionException, SecurityException, SystemException, TypeConstraintException, TypeNotPresentException, UndeclaredThrowableException, UnknownAnnotationValueException, UnknownElementException, UnknownTypeException, UnmodifiableSetException, UnsupportedOperationException, WebServiceException
NullPointerException、IndexOutOfBoundsException都是比较常见的运行期异常。
举例:
public static void main(String[] args) { int[] array = new int[10]; array = null; System.out.println(array.length); }
Exception in thread "main" java.lang.NullPointerException at lang.Object.ExceptionTest.main(ExceptionTest.java:18)
关于NPE异常
当应用程序试图在需要对象的地方使用 null
时,抛出该异常。这种情况包括:
- 调用
null
对象的实例方法。 - 访问或修改
null
对象的字段。 - 将
null
作为一个数组,获得其长度。 - 将
null
作为一个数组,访问或修改其时间片。 - 将
null
作为Throwable
值抛出。
应用程序应该抛出该类的实例,指示其他对 null
对象的非法使用。
2. 运行期异常的处理
异常可以使用catch进行捕获,然后进行处理。
@Test public void testArithmeticException() { try { int result = 10 / 0; System.out.println("try中异常之后的代码不会执行"); } catch (ArithmeticException e) { System.out.println("进行异常处理:"); System.out.println(e.getMessage()); } System.out.println("try...catch之后的代码可以执行"); }
3. 运行期异常的抛出
不进行处理,可以将异常抛给上层,由上层进行处理。
public static void main(String[] args) { try { testNullPointerException(); } catch (NullPointerException e) { e.printStackTrace(); System.out.println("异常由上层进行处理"); } //如果前面的代码中发生异常,后面的代码就不会执行 System.out.println("调用成功"); } public static void testNullPointerException() { int[] array = new int[10]; array = null; //由于执行者不处理异常,异常会自动抛出 int length = array.length; System.out.println(length); }
以上是关于java异常处理及自定义异常的使用的主要内容,如果未能解决你的问题,请参考以下文章