Java

如何处理java中short类型的异常

小樊
85
2024-09-14 04:44:51
栏目: 编程语言

在Java中,处理short类型的异常与处理其他数据类型的异常相似

  1. 使用try-catch语句捕获异常:
public class ShortExceptionHandling {
    public static void main(String[] args) {
        try {
            short num1 = 10;
            short num2 = 5;
            short result = divide(num1, num2);
            System.out.println("Result: " + result);
        } catch (ArithmeticException e) {
            System.out.println("Error: Division by zero");
        }
    }

    public static short divide(short a, short b) {
        if (b == 0) {
            throw new ArithmeticException("Division by zero");
        }
        return (short) (a / b);
    }
}
  1. 使用throws关键字将异常传递给调用者:
public class ShortExceptionHandling {
    public static void main(String[] args) {
        short num1 = 10;
        short num2 = 5;
        try {
            short result = divide(num1, num2);
            System.out.println("Result: " + result);
        } catch (ArithmeticException e) {
            System.out.println("Error: Division by zero");
        }
    }

    public static short divide(short a, short b) throws ArithmeticException {
        if (b == 0) {
            throw new ArithmeticException("Division by zero");
        }
        return (short) (a / b);
    }
}
  1. 使用自定义异常处理:
public class ShortExceptionHandling {
    public static void main(String[] args) {
        short num1 = 10;
        short num2 = 5;
        try {
            short result = divide(num1, num2);
            System.out.println("Result: " + result);
        } catch (CustomDivideByZeroException e) {
            System.out.println("Error: " + e.getMessage());
        }
    }

    public static short divide(short a, short b) throws CustomDivideByZeroException {
        if (b == 0) {
            throw new CustomDivideByZeroException("Division by zero");
        }
        return (short) (a / b);
    }
}

class CustomDivideByZeroException extends Exception {
    public CustomDivideByZeroException(String message) {
        super(message);
    }
}

这些示例展示了如何处理short类型的异常。你可以根据实际需求选择合适的方法来处理异常。

0
看了该问题的人还看了