在Java中,處理short類型的異常與處理其他數據類型的異常相似
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);
}
}
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);
}
}
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類型的異常。你可以根據實際需求選擇合適的方法來處理異常。