「Java例外案例」java典型案例
今天给各位分享Java例外案例的知识,其中也会对java典型案例进行解释,如果能碰巧解决你现在面临的问题,别忘了关注本站,现在开始吧!
本文目录一览:
- 1、java抛出例外
- 2、关于Java的例外处理
- 3、java编程 例外异常处理
- 4、java程序运行时出现例外
- 5、java编程 例外异常
java抛出例外
method(1);//这个传的是1,在method这个方法里面的那个if (n=0)的条件就成立了,就会执行
if (n=0) {
int s=1;
for(int i=1;in+1;i++) s=s*i;
System.out.println("n!="+s);
}这里面的东西
到了 if (n0)这里它不成立..里面的东西不执行
method(-1);//而这个传的是-1,在method这个方法中if (n=0)不成立.里面的东西不执行..if (n0)条件成立 就 抛出throw new ArgumentException("n0")异常
关于Java的例外处理
楼主,不是特别清楚您要表达的意思。你说的“例外”是指异常吗?
充实一下你的异常处理的示例代码吧:
public int f(){
int i = 3;
try{
i = 30/i;
return i; //a
}catch(Exception ex){
ex.printStackTrace(); //b
}finally{
return 0; //c
}
}
}
这个程序不会返回10,而永远会返回0,因为程序中的finally块是必须执行的,在程序执行到a位置的时候,遇到了return ,程序会先不执行它,而是进入finally块,也就是c的位置去执行,所以就执行了 return 0
希望能帮到你,还有疑问的话请把问题描述的清晰一些。
java编程 例外异常处理
代码:
/**
* 测试用例1
*
*/
public class Test1 {
public static void main(String[] args) {
System.out.println("改程序实现:输入一组数据保存在数组,读取数组某个位置的值。");
System.out
.println("输入一个整数 n ,表示接下来有 n 个整数,接着输入 n 个整数,然后输入一个整数表示要读取数据的下标。");
Scanner scanner = new Scanner(System.in);
int n = Integer.valueOf(scanner.nextLine());
int[] arr = new int[n];
for (int i = 0; i n; i++) {
arr[i] = Integer.valueOf(scanner.nextLine());
}
int index = Integer.valueOf(scanner.nextLine());
System.out.println("下标为 " + index + " 的元素:" + arr[index]);
scanner.close();
}
}
测试用例2:
代码:
/**
* 测试用例2
*
*/
public class Test2 {
public static void main(String[] args) {
System.out.println("改程序实现:输入一组数据保存在数组,读取数组某个位置的值。");
System.out
.println("输入一个整数 n ,表示接下来有 n 个整数,接着输入 n 个整数,然后输入一个整数表示要读取数据的下标。");
Scanner scanner = new Scanner(System.in);
int n = Integer.valueOf(scanner.nextLine());
int[] arr = new int[n];
for (int i = 0; i n; i++) {
arr[i] = Integer.valueOf(scanner.nextLine());
}
int index = Integer.valueOf(scanner.nextLine());
if (index = n) {
System.out.println("Array out of bounds");
}
scanner.close();
}
}
java程序运行时出现例外
ClassCastException 是类型转换异常.
在这里父类不能被强转为子类. 如果把 Base b = new Base(); 换为
Base b = new Sub();就不会出错
java编程 例外异常
public static void main(String[] args) throws CustomException{
Scanner scanner = new Scanner(System.in) ;
while(scanner.hasNext()){
String x = scanner.nextLine() ;
String y = scanner.nextLine() ;
int product = product(Integer.parseInt(x), Integer.parseInt(y)) ;
System.out.println(product);
if(product 0){
throw new CustomException(" throws Exception ") ;
}
}
}
public static int product(int x,int y){
return x * y ;
}
static class CustomException extends Exception{
public CustomException(String msg){System.out.println(msg) ;}
}
关于Java例外案例和java典型案例的介绍到此就结束了,不知道你从中找到你需要的信息了吗 ?如果你还想了解更多这方面的信息,记得收藏关注本站。
发布于:2022-11-22,除非注明,否则均为
原创文章,转载请注明出处。