"Dark Horse programmer Jinan Campus" Java Basics: Exceptions

Source: Internet
Author: User
Tags getmessage throw exception throwable try catch

Exception:

Java运行时期发生的问题就是异常。Java中运行时发生的除了异常Exception还有错误Error。异常:通常发生可以有针对性的处理方式的。错误:通常发生后不会有针对性的处理方式。Error的发生往往都是系统级别的问题,都是jvm所在系统发生的并反馈给jvm的。无法针对处理,只能修正代码。

When writing a procedure, it is important to consider the issue of the program. So the definition program needs to consider the robustness of the program. Add some logical judgments.

Characteristics of the anomaly system:

All classes and their subclass objects in an exception system are parabolic. This means that it can be manipulated by the throw and throws keywords.

The main method is how to handle exceptions.

    A:在main里面编写代码进行处理    B:交给jvm自己进行处理。采用的是jvm的默认处理方式。      其实就是相当于调用了异常对象的printStackTrace()方法。

The study of Throwable class

    getMessage():获取异常信息,返回字符串。    toString():获取异常类名和异常信息,返回字符串。    printStackTrace():获取异常类名和异常信息,以及异常出现在程序中的位置。返回值void。

Exception application:

if (arr==null)//null pointer throws an exception

{    thrownewNullPointerException("arr指向的数组不存在");}

if (index<0| | index>=arr.length)//Corner label out of bounds throw exception

{    thrownewArrayIndexOutOfBoundsException("错误的角标,"+index+"索引在数组中不存在");}

if (age<0| | age>200)//Invalid argument throws an exception

{    thrownewIllegalArgumentException(age+",年龄数值非法");}

Custom Exceptions:

自定义异常被抛出,必须是继承Throwable,或者继承Throwable的子类。该对象才可以被throw抛出,可以将自定义的异常继承RuntimeException.在java虚拟机运行时异常以及其子类都无需进行声明

Classnoageexception extendsruntimeexception

  {      /*      为什么要定义构造函数,因为看到Java中的异常描述类中有提供对问题对象的初始化方法。      */      NoAgeException()      {          super();      }      NoAgeException(String message)      {          super(message);// 如果自定义异常需要异常信息,可以通过调用父类的带有字符串参数的构造函数即可。      }  }

There are two kinds of principle anomalies:

1, compile-time exception (Java.lang.Excpetion): The exception that the compiler detects. The JVM thinks the program itself has problems to declare or capture.

2, run-time exception (Java.lang.RuntimeExcpetion): The exception that the compiler does not detect. No declaration is required. It is also possible, if declared, to have the caller give the method of processing.

The difference between inheriting exception and inheriting runtimeexcpetion:

The Exception class and its subclasses are a form of throwable that identifies the conditions that a reasonable application wants to capture.

(The program has a problem, Java believes that the program itself is a hidden danger, need to be captured or declared)

RuntimeException is a superclass of exceptions that might be thrown during the normal operation of a Java virtual machine.

Any subclass of RuntimeException that may have been thrown but not captured during the execution of the method does not need to be declared in the throws clause.

(The exception is not the function itself, but the user passes the parameter error while using the function, which causes the function to fail.) )

To inherit the exception, it is necessary to throws the declaration, a declaration informs the caller to capture, and once the problem has been handled the caller's program will continue to execute.

However, if the data for the object is used, the result is a failure.

Inheriting runtimeexcpetion, it is not necessary to declare the throws, it is not possible to write the capture code, because the call is not aware of the problem at all.

Once an exception occurs, the caller program stops, and the JVM displays the information to the screen, allowing the caller to see the problem and fix the code. When throwing one with throws, if the exception belongs to the RuntimeException system, we do not have to deal with it in the place of the call. (Subclasses of RuntimeException and RuntimeException)

Declaration: Identify the problem and report it to the caller. If a compile-time exception is thrown inside a function through a throw, it must be declared by throws to be handled by the caller.

Capture: An exception-targeted statement is captured in Java.

Statement:

Try

{

//需要被检测的语句。

}

catch (Exception class variable)//parameter.

{

//异常的处理语句。

}

Finally

{

//一定会被执行的语句,并且在return之前运行。

}

Try catch: Makes exception detection of code and passes the detected exception to catch processing.

Try finally: Exception detection of the code, after an exception is detected because there is no catch, so the default JVM will be thrown.

异常是没有捕获处理的。但是功能所开启资源需要进行关闭,所以finally。只为关闭资源。

Try Catch finally: detects an exception, passes it to catch processing, and defines the resource release.

Details of the use of exceptions in inheritance or implementation:

1,子类覆盖父类方法时,如果父类的方法声明异常,子类只能声明父类异常或者该异常的子类,或者不声明。2,当父类方法声明多个异常时,子类覆盖时只能声明多个异常的子集。3,当被覆盖的方法没有异常声明时,子类覆盖时时无法声明异常的。举例:父类存在这种情况,接口也有这种情况,问题:接口中没有声明异常,而实现的子类覆盖方法时发生了异常,怎么办?无法进行throws声明,只能catch的捕获。问题处理不了catch中继续throw抛出,但是只能将异常转换成RuntimeException子类抛出。

Exception conversions

For exceptions that can be temporarily resolved but not fundamentally resolved,

It is necessary to continue to declare throws out and convert it to a problem that the caller can solve.

System.out.println (E.tostring ());//Print the name of the exception + information about the exception.

System.out.println (E.getmessage ());//print exception information.

When multiple exceptions are captured at the same time, remember a principle:

Catch the small first, then catch the big.

**finally: is always executed unless you exit the JVM. System.exit (0);

2 Interview questions.

: final,finally,finalize difference.

Final is the ultimate meaning. It can be used to decorate classes, member variables, and member methods.

The class it modifies cannot be inherited, it modifies the variable at a constant amount, and the method it modifies cannot be overridden.

Finally: is the key word inside the exception handling.

Its code is always executed. Special case: The JVM exits before executing it. System.exit (0);

Finalize: Is a method in the object class.

It is the way that the garbage collector is called.

: If there is a return statement in the catch, will the code in the finally execute?

Is it before the return, or after the return?

The code in the finally is executed before the return.

The difference between throws and throw

A: There can be no throw when there is throws.

When there is a throw, if the exception of throw throws is the exception system, then there must be throws declared on the method.

B:throws is used for the declaration of a method, followed by the exception class name, which can be followed by a comma separated by a number of exception classes

Throw is used in the method body, followed by an exception object name

"Dark Horse programmer Jinan Campus" Java Basics: Exceptions

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.