English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
异常是程序执行期间发生的问题(运行时错误)。发生异常时,程序会突然终止,并且生成异常的行之后的代码将永远不会执行。
import java.util.Scanner; public class ExceptionExample { public static void main(String args[]) { Scanner sc = new Scanner(System.in); System.out.println("请输入第一个数字: "); int a = sc.nextInt(); System.out.println("请输入第二个数字: "); int b = sc.nextInt(); int c = a/b; System.out.println("The result is: ");+c); } }
Output Result
Enter first number: 100 Enter second number: 0 Exception in thread "main" java.lang.ArithmeticException: / by zero at ExceptionExample.main(ExceptionExample.java:10)
You cannot use multiple try blocks with a single catch block. Each try block must be immediately followed by a catch or last. However, if you try to use a single catch block for multiple try blocks, a compile-time error will be generated.
The following Java program attempts to use a single catch block for multiple try blocks.
class ExceptionExample{ public static void main(String args[]) { int a,b; try { a=Integer.parseInt(args[0]); b=Integer.parseInt(args[1]); } try { int c=a/b; System.out.println(c); }catch(Exception ex) { System.out.println("Please pass the args while running the program"); } } }
ExceptionExample.java:4: error: 'try' without 'catch', 'finally' or resource declarations try { ^ 1 error