Explain the built-in exceptions of Java and the methods of creating custom exception subclasses

Built in abnormal subclass

In the standard package Java Lang, Java defines several exception classes. Some of these have been used in previous examples. These exceptions are generally subclasses of the standard runtimeException class. Because Java Lang is actually introduced by all Java programs, and most exceptions derived from runtimeException are automatically available. Moreover, they do not need to be included in the throws list of any method. In the Java language, This is called an unchecked exception (unchecked exceptions). Because the compiler does not check it to see whether a method handles or throws these exceptions. The unchecked exceptions defined in java.lang are listed in Table 1. Table 2 lists the exceptions defined by java.lang that must be included in the throws list of methods. If these methods can generate one of these exceptions but can't handle it by themselves. These are called exceptions Checked exceptions. Java defines several other exception types related to different class libraries.

Table 1: Java Unchecked exception subclass defined in Lang

Create your own exception subclass using java

Despite most common errors in Java's built-in exception handling, you may want to create your own exception types to handle the special situations you apply. This is very simple: just define a subclass of exception (exception is, of course, a subclass of throwable). Your subclasses don't need to actually execute anything -- their existence in the type system allows you to use them as exceptions.

The exception class itself does not define any methods. Of course, it inherits some of the methods provided by throwable. Therefore, all exceptions, including those you create, can get the method defined by throwable. These methods are shown in Table 3. You can also override one or more of these methods in the exception class you create. Table 3 methods defined by throwable

This example defines a subclass myexception of exception. This subclass is very simple: it contains only a constructor and an overloaded toString () method that displays outliers. The exceptiondemo class defines a compute () method. This method throws a myexception object. This exception is thrown when the integer parameter of compute() is greater than 10.

The main () method sets up an exception handler for myexception, and then calls compute () with a legal value and an illegal value to display the different paths through which the code is executed. Here are the results:

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>