How to use the Java keywords throw, throws, and Throwable
throw means "throw, throw, throw". Throw, Throws and Throwable are all used for exception handling.
1. Throwable
Throwable is the top-level parent class of the exception handling branch in Java. The implementation of all other exception handling relies on Throwable
Open the official Java documentation ( Java8 version), find Throwable, its direct subclasses are Error and Exception.
#The characteristic of Error and Exception is that the Error exception program cannot handle it and can only be left to manual intervention to modify the code, such as stack overflow, heap overflow, etc.; while Exception exception It can be detected in advance and dealt with effectively.
1.1 Extension-Error
Among Errors, common ones include stack overflow, heap overflow, etc.
For example, StackOverflowError
public class ErrorTest { public static void main(String[] args) { main(args); } }
Infinite recursion, executing this program will report a stack overflow exception.
Another example is the heap exception, OutOfMemoryError
public class ErrorTest { public static void main(String[] args) { Integer[] testArray = new Integer[1024*1024*1024]; } }
1.2 Extension-Exception
In Exception There are many exceptions that we are familiar with, such as NullPointerException (null pointer exception), ArrayIndexOutOfBoundsException (array subscript out of bounds), NumberFormatException (number formatting exception), etc.
public class ExceptionTest { public static void main(String[] args) { int[] testArray = null; System.out.println(testArray[0]); //空指针异常 } }
public class ExceptionTest { public static void main(String[] args) { int[] testArray = new int[3]; System.out.println(testArray[3]); //数组下标越界 } }
public class ExceptionTest { public static void main(String[] args) { String num = "abc"; System.out.println(Integer.parseInt(num)); //数字格式化异常 } }
2. throws
throws is applied at the method declaration to indicate the types of exceptions that may occur when this method is executed. Once an exception occurs when the method is executed, an object of the exception class will be generated at the exception code. When this object meets the exception type after Throws, it will be thrown. There are two processes here. When there is an exception in the code
1. Generate an exception object;
2. throws captures this exception and throws the exception object
throws and try-catch-finally together are called two ways of exception handling.
try-catch-finally actively handles the exception when an exception occurs, so that the program can continue to execute; while throws catches the exception and throws the exception object upward without actually handling the exception.
The so-called throwing exception object upward is to hand over the exception object to the caller for processing. For example, method A calls method B, B throws an exception through throws, and A can choose to use try-catch-finally to handle it. Exceptions can also be thrown upward through throws until the exception is actually handled. If there is no way to handle exceptions, the exception object will eventually be thrown to the JVM, causing the program to stop running.
@Test public void throwsTest(){ //调用者解决抛出的异常 try{ formatChange("abc"); } catch (NumberFormatException e){ System.out.println("转换格式错误!"); } catch (Exception e){ System.out.println("出现错误"); } } private int formatChange(String str) throws NumberFormatException{ //出现异常向上抛出 return Integer.parseInt(str); }
2.1 Extension
——How to choose try-catch-finally or throws?
When there is an exception in a method that needs to be handled, in most cases, you can either choose try-catch-finally to handle the exception directly, or you can choose throws to throw the exception upward and leave it to the caller to handle. (When an exception is thrown at the end, there must be one party who actually handles the exception. How to deal with it? Let’s use try-catch-finally.) You are relatively free in choice. However, when the following two situations occur, you need to follow certain rules. (If you have anything to add, please point it out).
If the overridden method in the parent class does not use throws to throw an exception, the method overridden by the subclass cannot use throws to throw an exception, which means that this situation Must use try-catch-finally to handle.
In method A, several other methods are called successively. These methods are executed in a progressive relationship and many of them have exceptions that need to be handled. In this case, it is recommended Several called methods use throws to throw upward exceptions. In method A, try-catch-finally is used to handle these exceptions uniformly.
Regarding the first one, this is a stipulation that the exception thrown by the overridden method in the subclass using throws must not be greater than the exception thrown by the overridden method in the parent class. scope. For example, if method B in the parent class throws NullPointerException, then the overridden method B in the subclass cannot throw exceptions such as Exception that have a wider scope than NullPointerException; if the overridden method in the parent class does not throw If any exception occurs, the subclass cannot throw an exception.
Why? Show a piece of code.
//假设父类中的方法B抛出NullPointerException异常,子类中的方法B可以抛出Exception private void test(ParentClassTest parent){ try{ parent.B(); } catch(NullPointerException e){ System.out.println("出现了空指针异常"); } }
In this example, assuming that method B in the parent class throws NullPointerException, the overridden method B in the subclass can throw Exception. Then if the parameters passed into the test method are instantiated objects of the parent class, then there is no problem in calling the test method. If the parameter passed in is an instantiated object of the subclass, and then the method B rewritten by the subclass is called, an Exception may be thrown, and the try-catch structure cannot suppress this exception. This is obviously an error. Reasonable operation.
针对第二条,假设方法A中调用了方法C、D、E,这三个方法都有可能产生异常,且存在递进关系,也就是D、E执行需要C执行完成、E执行依赖C、D执行完成。那么就推荐在C、D、E中向上抛出异常,在方法A中集中处理。为什么?如果C、D、E都是向上抛出异常,而A使用try-catch-finally去处理这个异常,如果某个方法真的出现异常,则不再继续执行。而如果C、D、E都使用try-catch-finally直接解决掉异常,那么即使产生了异常,方法A也不会接收到异常的产生,那么还会接着往下执行,但是C出现了异常,再执行D、E没有任何意义。
3. throw
如果在程序编写时有手动抛出异常的需求,则可以使用throw
throw使用在方法体内。与try-catch-finally和throws都不同,异常处理的两个阶段:1.遇到异常,生成异常对象;2.捕获到异常,进行抛出或处理。try-catch-finally和throws都处在第二个阶段,都是捕获到异常后的相关处理,一般使用系统根据异常类型自动生成的异常对象进行处理。而throw应用在第一阶段,手动地产生一个异常对象。
举一个例子,判断一个数值是否为非负数,如果为负数,则抛出异常。
class ThrowTest{ private int Number; public void judge(int num){ if(num>=0){ this.Number = num; } else{ throw new RuntimeException("传入参数为负数"); } } }
@Test public void test2(){ ThrowTest throwTest = new ThrowTest(); throwTest.judge(-100); }
成功抛出异常。
使用try-catch捕获一下异常。
@Test public void test2(){ ThrowTest throwTest = new ThrowTest(); try{ throwTest.judge(-100); } catch (RuntimeException e){ System.out.println(e.getMessage()); } }
如果把throw抛出的异常改为Exception,则直接报错,也就是不能编译。Exception包含两种异常:编译时异常和运行时异常,前者在编译前就要检查是否有可能产生编译时异常;后者是在编译后运行时才会判断的异常。而throw new Exception包含了编译时异常,需要显式处理掉这个异常,怎么处理?try-catch-finally或者throws
class ThrowTest{ private int Number; public void judge(int num) throws Exception{ if(num>=0){ this.Number = num; } else{ throw new Exception("传入参数为负数"); } } }
调用方也要随着进行更改。
@Test public void test2(){ ThrowTest throwTest = new ThrowTest(); try{ throwTest.judge(-100); } catch (RuntimeException e){ System.out.println(e.getMessage()); } catch (Exception e){ System.out.println(e.getMessage()); } }
3.1 扩展
——自定义异常类
throw还可以抛出自定义异常类。
自定义异常类的声明需要继承于现有的异常体系。
class MyException extends RuntimeException{ static final long serialVersionUID = -703489719076939L; //可以认为是一种标识 public MyException(){} public MyException(String message){ super(message); } }
此时我们可以抛出自定义的异常
class ThrowTest{ private int Number; public void judge(int num) throws MyException{ if(num>=0){ this.Number = num; } else{ throw new MyException("不能输入负数"); } } }
调用者修改
@Test public void test2(){ ThrowTest throwTest = new ThrowTest(); try{ throwTest.judge(-100); } catch (MyException e){ System.out.println(e.getMessage()); } }
The above is the detailed content of How to use the Java keywords throw, throws, and Throwable. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.
