「java异常写法」java异常怎么写
本篇文章给大家谈谈java异常写法,以及java异常怎么写对应的知识点,希望对各位有所帮助,不要忘了收藏本站喔。
本文目录一览:
如何用Java程序来编写一个异常?
class
MyException
extends
Exception
//自定义的异常类
继承Exception类
{
private
String
exceptionName;
//定义一个私有变量,用来为自定义异常
public
MyException(){}
//创建一个无参数的构造函数
public
MyException(String
exceptionName){
//创建一个有参数的构造函数,传入的参数为前面定义的异常名称
this.exceptionName=exceptionName;
}
public
String
getExceptionName(){
//定义一个方法,提供给外部来获取私有变量
return
this.exceptionName;
}
public
static
void
main(String
[]
args){
try{
System.out.println("自定义的异常类对象");
throw
new
MyException("自定义的异常");//抛一个自定义的异常类对象,传入的参数就是给控制台看的异常
}catch(MyException
e){
System.out.println("异常信息:"+e.getExceptionName());
}
}
}
我已经尽力你……你懂的!
Java中异常处理语句有哪些?
JAVA使用try-catch语句来处理异常。
将有可能出现的异常操作放在try-catch的try部分,一旦try部分抛出异常对象,或调用某个可能抛出异常对象的方法,并且该方法抛出了异常对象,那么try立即结束执行,转向catch部分。所以程序将发生异常后的处理放在catah部分。
用java编写异常
public class NoOprandException{
String a;
String b;
public NoOprandException(String a,String b){
this.a=a;
this.b=b;
}
public String errorException(){
if((a==nulla.equals(""))(b==nullb.equals(""))){
return "NoOprand错误!";
}
return;
}
}
public class OnlyOneException{
String a;
String b;
public OnlyOneException(String a,String b){
this.a=a;
this.b=b;
}
public String errorException(){
if((a==nulla.equals(""))||(b==nullb.equals(""))){
return "OnlyOne错误!";
}
return;
}
}
public class a{
public static void main(String[] args){
Scanner scan1=new Scanner(System.in);
Scanner scan2=new Scanner(System.in);
String line1=scan1.nextLine();
String line2=scan2.nextLine();
try{
throw new OnlyOneException(line1,line2);
}catch(OnlyOneException e){
System.out.print(e);
System.out.exit(0);
}
try{
throw new NoOprandException(line1,line2);
}catch(NoOprandException e){
System.out.print(e);
System.out.exit(0);
}
}
}
需要Java中的异常语句实例
try{
int[] a=new int[]{1,2};
Object x=new Integer(0);
System.out.println(a[2]);//数组下标越界
Integer.parseInt("123String");//数字格式化异常
System.out.println((String)x);//强制类型转换异常
Class.forName("com.buhaowan.HelloWorld");//类加载异常
}catch(ArrayIndexOutOfBoundsException e){
System.out.println("数组下标越界异常");
}catch(NumberFormatException e){
System.out.println("数字格式化异常");
}catch(ClassCastException e){
System.out.println("强制类型转换异常");
}catch(ClassNotFoundException e){
System.out.println("类加载异常");
}catch(Exception e){
}
java异常写法的介绍就聊到这里吧,感谢你花时间阅读本站内容,更多关于java异常怎么写、java异常写法的信息别忘了在本站进行查找喔。
发布于:2022-11-30,除非注明,否则均为
原创文章,转载请注明出处。