Java 异常
2021/7/26 17:09:14
本文主要是介绍Java 异常,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
声明异常:throws
抛出异常:throw
public class CircleWithExceptionTest { public static void main(String[] args){ try{ CircleWithException c1 = new CircleWithException(5); CircleWithException c2 = new CircleWithException(-5); CircleWithException c3 = new CircleWithException(0); } catch(IllegalArgumentException ex){ System.out.println(ex); } System.out.println("Number of objects created: " + CircleWithException.getNumberOfObjects()); } } class CircleWithException{ private double radius; private static int numberOfObjects = 0; public CircleWithException(){ this(1.0); } public CircleWithException(double newRadius){ setRadius(newRadius); numberOfObjects ++; } public void setRadius(double newRadius) throws IllegalArgumentException{ if(newRadius >= 0) radius = newRadius; else throw new IllegalArgumentException("Radius cannot be negative"); } public double getRadius(){ return radius; } public static int getNumberOfObjects(){ return numberOfObjects; } public double findArea(){ return (radius * radius * 3.14159); } } // 运行结果 /* java.lang.IllegalArgumentException: Radius cannot be negative Number of objects created: 1 */
public class DivideException { public static void main(String[] args){ compute(); } public static void compute(){ try{ divide(5,0); } catch(Exception e){ System.out.println(e.getMessage()); } } public static void compute2() throws Exception{ divide(5,0); } public static void divide(int a, int b) throws Exception{ if(b == 0){ throw new Exception("两数相除,除数不能为0!"); } else{ System.out.println("The result is " + (a/b) ); } } } // 运行结果 /* 两数相除,除数不能为0! */
这篇关于Java 异常的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-11-19JAVA分布式id教程:轻松入门与实践
- 2024-11-19Java高并发教程:入门与实践指南
- 2024-11-19JAVA高并发直播教程:新手入门指南
- 2024-11-19Java高并发直播教程:入门与实践指南
- 2024-11-19Java微服务教程:初学者快速入门指南
- 2024-11-19JAVA微服务教程:新手入门的详细指南
- 2024-11-19Java微服务教程:从零开始搭建你的第一个微服务应用
- 2024-11-19Java项目开发教程:初学者必备指南
- 2024-11-19Java项目开发教程:新手快速入门指南
- 2024-11-19Java项目开发教程:零基础入门到实战