Java 自定义异常捕获
编写一个程序,将字符串转换成数字。请使用try-catch语句处理转换过程中可能出现的异常。
JAVA中提供了自定义异常类,虽说尽量使用定义好的类,但是有时候还是会使用到自定义异常类。
自定义异常类格式如下:
1 2 3 4 5 6 |
class /*自定义异常类名*/ extends Exception { public /*自定义异常类名*/ //相当于重写其构造函数{ super("/*输出的信息*/ "); } } |
自定义异常类的调用格式如下:
1 2 3 4 5 6 7 8 9 |
try { //有可能出现异常的代码; } catch (Exception e) //将异常捕获,放进类e中 { //对异常进行处理 } finally { //最后处理完后执行的代码 } |
可能出现异常的代码写法如下:
1 |
public static int StringtoInt(String s) throws TooLong,ZeroLength,InvalidChar |
开始和普通函数写法一样,这里输入一个字符串,返回一个整型是本题目要求,后面throws跟有可能出现的异常类名。从这里我们也可以看到,throws是针对类的,throw是针对实例的。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
{ int len,i,ans= 0 ; boolean flag= true ; len=s.length(); for (i= 0 ;i<=len- 1 ;i++) { if (s.charAt(i)< '0' ||s.charAt(i)> '9' ) { flag= false ; break ; } } if (s.length()>= 6 ) { throw new TooLong(); //遇到异常抛出 } else if (s.length()== 0 ) { throw new ZeroLength(); } else if (flag== false ) { throw new InvalidChar(); } for (i= 0 ;i<=len- 1 ;i++) { ans=ans+(s.charAt(i)- '0' )*(( int )Math.pow( 10 ,len-i- 1 )); } return ans; } |
本题完整代码如下:
异常类型有:空字符,超过长度字符串和含有非法字符的字符串。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 |
import java.util.*;
class InvalidChar extends Exception { public InvalidChar() { super ( "字符串中含有非法字符,无法转换为整型" ); } }
class TooLong extends Exception { public TooLong() { super ( "字符串长度过长,无法转换成整型" ); } }
class ZeroLength extends Exception { public ZeroLength() { super ( "长度是零,无法转换成整型" ); } }
public class ExceptionTester { public static int StringtoInt(String s) throws TooLong,ZeroLength,InvalidChar { int len,i,ans= 0 ; boolean flag= true ; len=s.length(); for (i= 0 ;i<=len- 1 ;i++) { if (s.charAt(i)< '0' ||s.charAt(i)> '9' ) { flag= false ; break ; } } if (s.length()>= 6 ) { throw new TooLong(); } else if (s.length()== 0 ) { throw new ZeroLength(); } else if (flag== false ) { throw new InvalidChar(); } for (i= 0 ;i<=len- 1 ;i++) { ans=ans+(s.charAt(i)- '0' )*(( int )Math.pow( 10 ,len-i- 1 )); } return ans; } public static void main(String args[]) { int a; String s; Scanner cin= new Scanner(System.in); System.out.println( "输入一个字符串" ); s=cin.nextLine(); try { a=StringtoInt(s); } catch (Exception e) { System.out.println(e.toString()); return ; } System.out.println(a+ "\n" + "没有异常被捕获" ); return ; } } |
常见的异常处理代码有e.toString(),e.getMessage(),e.printStackTrace()等等。
自定义异常Exception
根据业务需要不用的异常打印不用类型的日志
1 2 3 4 5 6 7 |
package com.cestbon.exception; public class RpcException extends Exception { /** * */ private static final long serialVersionUID = 6554142484920002283L; } |
继承重写Exception方法即可~
以上为个人经验,希望能给大家一个参考,也希望大家多多支持。
原文链接:https://blog.csdn.net/sunny1996/article/details/51292275