JAvaベース_10
2599 ワード
1、javaの異常処理メカニズムには5つのキーワードが必要である:try catch finally throw throws 2、一般的な例外処理フォーマット:try{//異常をトリガする可能性のあるコードセグメント}catch(Exception e){//異常トリガ後に異常を処理するコードセグメント}finally{//異常がトリガするかどうか、キャプチャするかどうかにかかわらず実行されるコードセグメント、//一般的にクリーンアップに用いられる}3、throwおよびthrowsは、例外をカスタマイズするために使用されます.throwは例外を放出するために使用され、throwsは私が放出する可能性がある例外を宣言するために使用されます.
import java.util.InputMismatchException;
import java.util.Scanner;
public class Entry {
public static void main(String[] args) throws AgeException {
// TODO Auto-generated method stub
int a, b = 0, c = 0;
a = 23;
Scanner in = new Scanner(System.in);
System.out.println(" ");
try
{
b = in.nextInt();
c = a / b;
}
catch (ArithmeticException ex)
{
System.out.println(" 0");
//System.exit(-1);
}
System.out.println("finally ");
System.out.println("c = " + c);
/*
People p1 = new People();
try
{
p1.setAge(675);
}catch (AgeException ex)
{
System.out.println(" ");
}*/
/*
int a, b = 0, c = 0;
a = 23;
Scanner in = new Scanner(System.in);
System.out.println(" ");
try
{
b = in.nextInt();
c = a / b;
}
catch (ArithmeticException ex)
{
System.out.println(" 0");
System.exit(-1);
}
catch (InputMismatchException ex)
{
System.out.println(" ");
System.exit(-1);
}
System.out.println("c = " + c);
//int a = 23;
//int b = a / 0;
//System.out.println("exception test");
*/
}
}
public class People {
private int age;
public void setAge(int age) throws AgeException
{
this.age = age;
if (age > 500)
{
throw new AgeException(500);
}
}
}
public class AgeException extends Exception{
public AgeException()
{
System.out.println(" , 0 150 ");
}
public AgeException(int maxAge)
{
System.out.println(" , 0 " + maxAge +" ");
}
}