Java异常处理习题

/*1、编写应用程序,从命令行传入两个整型数作为除数和被除数。要求程序中捕获NumberFormatException 异常和ArithmeticException 异常,而且无论在哪种情况下,“总是被执行”这句话都会在控制台输出。 */

import java.util.Scanner;

public class NumberExeption {

//正则表达式数字验证

public static boolean isNumber(String str)

    {

        java.util.regex.Pattern pattern=java.util.regex.Pattern.compile("[0-9]*");

        java.util.regex.Matcher match=pattern.matcher(str);

        return match.matches();

    }

public static void main(String[] args) {

Scanner scan=new Scanner(System.in);

System.out.println("请输入第一个数字:");

String s1=scan.next();

System.out.println("请输入第二个数字");

String s2=scan.next();

int n1,n2;

try {

n1=Integer.parseInt(s1);

n2=Integer.parseInt(s2);

System.out.println(n1/n2);

} catch (NumberFormatException|ArithmeticException e) {

e.printStackTrace();

}

finally {

System.out.println("It is always running!");

}

}

}

运行图:

/*2、编写一个检查给定的数字的数据类型是否为byte的程序,

* 如果此数字超出byte数据类型表示的数的范围,则引发用户自定义的异常ByteSizeException,

* 并显示相应的错误信息(知识点:自定义异常)

* 步骤1:创建用户自定义异常类ByteSizeException

* 步骤2:在main方法中编写逻辑代码

* 步骤3:运行并测试

*/

public class ByteSizeException extends Exception {

public ByteSizeException() {

super("此数字超出了byte数据类型表示的数的范围");

}

}

测试程序:

public class ByteTest {

public static void ByteEcep(int number) throws ByteSizeException {

if (number > 127 || number <= -128) {

throw new ByteSizeException();

}

}

public static void main(String[] args) {

try {

ByteEcep(565);

} catch (ByteSizeException e) {

e.printStackTrace();

}

}

}

运行图:

/*

* 3、编写一个方法,比较两个字符串。假如其中一个字符串为空,

* 会产生NullPointerException异常,在方法声明中通告该异常,

* 并在适当时候触发异常,然后编写一个程序捕获该异常。

*/

public class NullPoint {

public static void NullPointed(String s1, String s2) throws NullPointerException {

if (s1 == null || s2 == null) {

throw new NullPointerException();

} else {

}

}

public static void main(String[] args) {

try {

String a = null;

String b = "bdn";

NullPointed(a, b);

} catch (NullPointerException e) {

e.printStackTrace();

}

}

}

运行图:

你可能感兴趣的:(Java异常处理习题)