Home > Java > Javagetting Started > body text

How exceptions are generated in java

王林
Release: 2020-07-31 16:04:03
forward
2671 people have browsed it

How exceptions are generated in java

Automatically generated: When the program encounters an error code, an exception will be generated and the program will terminate.

(Recommended tutorial: java introductory tutorial)

Manually generated: throw new exception class name ();

throw must be defined in the method body , used to throw an exception of type Throwable. The program will terminate immediately after the throw statement, and the statements following it cannot be executed. Then it will search from the inside out for a try block that contains a matching catch clause in all try blocks containing it (possibly in the upper-level calling function).

(Video tutorial recommendation: java video tutorial)

Example:

Manually throwing an exception

package prac;
public class t2 {
	public static void main(String[] args) throws Exception {
		// TODO Auto-generated method stub
		m1();
	}

	public static void m1() throws Exception {
		System.out.println("m1----------start");
		m2();
		// 手动抛出受查异常
		throw new Exception();
		//System.out.println("m1----------end");
	}

	public static void m2() {
		System.out.println("m2----------start");
		// 手动抛出运行时异常,需要携带信息“程序因为异常而终止”
		throw new RuntimeException("程序因为异常而终止");
		//System.out.println("m2----------end");
	}
}
程序运行结果为:
m1----------start
m2----------start
Exception in thread "main" java.lang.RuntimeException: 程序因为异常而终止
	at prac.t2.m2(t2.java:31)
	at prac.t2.m1(t2.java:21)
	at prac.t2.main(t2.java:16)
Copy after login

The above is the detailed content of How exceptions are generated in java. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template