登录
首页 >  文章 >  java教程

项目 优先使用标准例外

来源:dev.to

时间:2024-12-06 13:10:00 348浏览 收藏

积累知识,胜过积蓄金银!毕竟在文章开发的过程中,会遇到各种各样的问题,往往都是一些细节知识点还没有掌握好而导致的,因此基础知识点的积累是很重要的。下面本文《项目 优先使用标准例外》,就带大家讲解一下知识点,若是你对本文感兴趣,或者是想搞懂其中某个知识点,就请你继续往下看吧~

1。重用标准异常的重要性

  • 标准异常使代码更容易被其他程序员理解和熟悉。
  • 提高 api 阅读和学习能力。
  • 减少内存消耗和类加载时间。

2。最重用的标准异常及其典型用途

  • illegalargumentexception:
  • 当参数具有不适当的值时使用。

示例:

public void setrepeatcount(int count) {
    if (count < 0) {
        throw new illegalargumentexception("count cannot be negative");
    }
    this.count = count;
}

illegalstateexception:

  • 当对象的状态不允许操作时启动。

示例:

public void start() {
    if (started) {
        throw new illegalstateexception("already started");
    }
    started = true;
}

空指针异常:

  • 禁止使用空参数时使用。

示例:

public void setname(string name) {
    if (name == null) {
        throw new nullpointerexception("name cannot be null");
    }
    this.name = name;
}

indexoutofboundsexception:
用于超出允许范围的索引。

示例:

public int getelement(int index) {
    if (index < 0 || index >= size) {
        throw new indexoutofboundsexception("index out of range");
    }
    return elements[index];
}

并发修改异常:

  • 在检测到对设计供单线程使用的对象进行并发修改时启动。

示例:

for (string item : list) {
    list.remove(item); // pode lançar concurrentmodificationexception
}

不支持的操作异常:

  • 当对象不支持某个操作时启动。

示例:

list<string> immutablelist = collections.unmodifiablelist(new arraylist<>());
immutablelist.add("item"); // lança unsupportedoperationexception

3。使用标准异常时的良好实践

  • 不要直接重用一般超类,如 exception、runtimeexception、throwable 或 error。
  • 根据记录的语义选择异常。
  • 仅在必要时使用标准异常的自定义子类。

4。例外情况之间的决定

  • 在不明确的情况下,请遵循以下准则:
  • 如果操作由于对象的状态而失败,则使用 illegalstateexception。
  • 如果失败是由无效参数引起的,则使用 illegalargumentexception。

示例:

  • 如果手牌大小无效,发牌方法可能会抛出 illegalargumentexception;如果牌组没有足够的牌,则发牌方法可能会抛出 illegalstateexception。

5。其他可重用的异常

  • arithmeticexception 和 numberformatexception 可以在数学运算和数字转换的上下文中使用。

示例:

public int divide(int numerator, int denominator) {
    if (denominator == 0) {
        throw new ArithmeticException("Division by zero");
    }
    return numerator / denominator;
}

项目 优先使用标准例外

结论
尽可能优先使用标准异常。它们使代码更清晰、更高效并且符合 java 语言实践。

终于介绍完啦!小伙伴们,这篇关于《项目 优先使用标准例外》的介绍应该让你收获多多了吧!欢迎大家收藏或分享给更多需要学习的朋友吧~golang学习网公众号也会发布文章相关知识,快来关注吧!

声明:本文转载于:dev.to 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>