注册 登录
编程论坛 JAVA论坛

问题:判断输入的字符串是否是16进制,如果不是就抛出异常,要求用自定义的HexFormatException异常

bug娃娃 发布于 2019-06-10 13:04, 4211 次点击
package homeWork5;

//import java.util.ArrayIndexOutOfBoundsException;
import
import java.util.InputMismatchException;
import java.util.Scanner;
 
public class T0822 {
 
    public static void main(String[] args) {
         q8();
    }
            static void q8(){     
            //create a Scanner
            Scanner in = new Scanner(System.in);
            
            try {
                //prompt the user to enter a string
                System.out.print("Enter a hex number:");
                String hex = in.nextLine();
               
                System.out.println("输入的数是否是正确的16进制数呢?" + hexPanDuan(hex));
            }
            catch(HexFormatException ex) {
                System.out.println("不是正确的16进制数");
            }            
        }
        
        public static boolean hexPanDuan(String hex) {            
            int count = 0;
            for(int i = 0 ; i < hex.length() ; i++) {
                char ch = hex.charAt(i);
                if(ch >= 'A' && ch <= 'Z' || ch >= '0' && ch <= '9')
                    count++;
            }
            if(count == hex.length())
                return true;
            else
                 throw new HexFormatException();
        }
}
   //HexFormatException异常的自定义
   class HexFormatException extends Exception{
       public HexFormatException() {
           super();
       }              
   }
这个会出现错误,1.Unhandle exception type HexFormatException ,2.Unreachable catch block for HexFormatException.This exception is never thrown from the try statement body.
求帮助
7 回复
#2
bug娃娃2019-06-10 13:17
说实在的我不是很会这种自定义异常,请大佬们帮帮我
#3
rind2019-06-10 15:48
没有捕获异常的方法中需要显式声明抛出异常
程序代码:
public static boolean hexPanDuan(String hex) throws HexFormatException {
...
    throw new HexFormatException();
...
}


#4
林月儿2019-06-10 17:04
1.Unhandle exception type HexFormatException ,
2.Unreachable catch block for HexFormatException.This exception is never thrown from the try statement body.
翻译翻译两句话什么意思
#5
bug娃娃2019-06-10 20:33
回复 4楼 林月儿
1.取消处理异常类型HexFormatException
2.HexFormatException无法访问的catch块
#6
bug娃娃2019-06-10 20:34
回复 3楼 rind
这个必须这么写吗?
#7
rind2019-06-12 12:27
回复 6楼 bug娃娃
看异常类型的,运行时异常(RuntimeExpection)不必显式声明。其他都需要。
#8
bug娃娃2019-06-14 22:56
回复 7楼 rind
喔喔,谢谢哈
1