跳至主要內容
產品桌面工具TASTECAD圖面檢視TASTEFILES檔案管理TASTEFTP檔案傳輸TASTESSH遠端工作空間TASTEZIP壓縮與解壓縮開發工具TASTECODERust 整合開發環境TASTESTUDIO整合開發與測試環境TASTEETL資料整合(ETL)伺服器TASTEREMOTE遠端桌面伺服器TASTEGEO空間資訊伺服器TASTEMAIL郵件工作空間開始使用下載文件購買所有產品
市集
資訊
技術資訊今日開發資訊開發文件程式語言RustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDartWeb 前端框架Next.jsReactVue.js · NuxtSvelteKitAngular伺服器框架Spring BootDjangoFastAPIASP.NET CoreNestJS · Express應用程式與桌面框架TauriFlutterReact NativeElectron演算法演算法基礎核心演算法進階演算法實務演算法
社群專案開發日誌提示詞AI 工具問題作品展示社群指南
合作技術傳授網站建置桌面應用程式建置發布與付款流程銷售合作夥伴聯絡我們
服務遠端桌面安裝包客製
TASTEDEV
產品

桌面工具

TASTECAD再複雜的圖面,也能輕鬆開啟TASTEFILES只挑需要的檔案,最快送達TASTEFTP讓檔案往來,走最俐落的路TASTESSH在你與伺服器之間,築起更穩固的連線TASTEZIP壓得更快,解得更安心

開發工具

TASTECODE在一個視窗中完成 Rust 應用程式的編輯、建置、偵錯與測試TASTESTUDIO從編輯到遠端測試,再到經核准的 AI 修正TASTEETL邊看數值,邊搬資料

伺服器

TASTEREMOTE在自己的伺服器上運行的遠端桌面TASTEGEO以 Rust 重新打造相容 GeoServer 的空間資訊伺服器TASTEMAIL把郵件的主導權拿回自己手上

開始使用

下載所有產品的最新版本文件各產品使用方法購買訂閱與永久授權所有產品一覽全部產品
所有產品
市集資訊
技術

資訊

今日開發資訊語言、框架、GitHub 與 AI 官方發布開發文件語言、框架與演算法指南

程式語言

RustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDart

框架

Web 前端框架Next.jsReactVue.js · NuxtSvelteKitAngular
伺服器框架Spring BootDjangoFastAPIASP.NET CoreNestJS · Express
應用程式與桌面框架TauriFlutterReact NativeElectron

演算法

演算法基礎複雜度分析 · 排序 · 搜尋 · 基礎資料結構 · 樹與堆積核心演算法圖形走訪 · 最短路徑與最小生成樹 · 動態規劃 · 貪婪演算法 · 分治法 · 回溯法進階演算法字串演算法 · 數學與數論 · 位元運算 · 線段樹 · 併查集實務演算法程式面試解題策略 · LRU 快取 · 速率限制 · 一致性雜湊
查看全部開發文件
社群
專案探索開發者與作品開發日誌決策與試錯提示詞可重複使用的指令AI 工具問題Claude、Codex、Gemini 的問題與替代做法作品展示已完成的成果社群指南我們如何公開打造
合作
技術傳授用 Rust 與 egui 打造原生應用程式網站建置10 種語言、帳號、文件與下載桌面應用程式建置Rust 與 egui,不用 WebView發布與付款流程簽章、MSI、deb、rpm、AppImage、雜湊銷售合作夥伴推薦即得 30%聯絡我們開發、合作與投資諮詢
服務
遠端桌面用瀏覽器連線你的電腦安裝包客製只裝需要的,設定預先放好
購買
繁
한국어EnglishDeutschEspañolFrançaisItalianoPortuguês (Brasil)日本語简体中文繁體中文
登入
登入
TASTEDEV

從小工具到更好的開發。

support@tastedev.net支持 TASTEDEV
產品產品系列購買文件下載市集客戶支援
社群專案開發日誌提示詞AI 工具問題作品展示
政策隱私權政策服務條款訂閱條款退款政策社群規範
帳戶登入註冊
訪客
今天
012345678901234567890123456789012345678901234567890123456789
昨天
012345678901234567890123456789012345678901234567890123456789
累計瀏覽
0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
公司名稱
GXSOFT
負責人
CHOI YOUNG GU
營業登記號碼
853-44-00368
地址
9F V24, 351 Gyeongin-ro, Michuhol-gu, Incheon, Republic of Korea
電話
+82-10-4404-1523
電子郵件
whitecalvin@tastedev.net
個人資料保護負責人
CHOI YOUNG GU

© 2026 TASTEDEV產品資訊以經驗證的開發原始碼為準。已發布·持續改進

Java 文件
Java
Getting StartedSyntax BasicsTypes and DataModules and PackagesErrors and TestingKey Concepts
討論

Java 指南 · 5/6

Errors and Testing

本章目前僅提供英文版。

Java reports failures with exceptions, split into checked exceptions, which the compiler makes you handle, and unchecked ones, which it does not. This chapter covers both, along with try-with-resources, custom exceptions, and unit testing with JUnit.

Checked versus unchecked

Every exception extends Throwable. The Exception branch covers problems a program can handle; the Error branch signals serious trouble you normally leave alone.

KindExamplesCompiler enforcement
CheckedIOException, SQLExceptionMust be caught or declared with throws
UncheckedNullPointerException, IllegalArgumentExceptionNot enforced
ErrorOutOfMemoryError, StackOverflowErrorUsually not handled

Unchecked exceptions extend RuntimeException and usually signal programming mistakes such as bad arguments. Checked exceptions model outside failures, like a missing file, that callers should expect.

package com.example.config;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

public class ConfigLoader {
    // a checked exception can be passed up to the caller with throws
    static String load(Path path) throws IOException {
        return Files.readString(path);
    }

    static int parsePort(String value) {
        int port = Integer.parseInt(value); // may throw NumberFormatException (unchecked)
        if (port < 1 || port > 65535) {
            throw new IllegalArgumentException("port out of range: " + port);
        }
        return port;
    }
}

try, catch, and finally

Wrap risky code in try and handle failures in catch clauses, most specific type first. One clause can catch several unrelated types with |. A finally block always runs.

try {
    String text = ConfigLoader.load(Path.of("app.conf"));
    int port = ConfigLoader.parsePort(text.strip());
    System.out.println("port = " + port);
} catch (NoSuchFileException | AccessDeniedException e) {
    System.err.println("Cannot access config file: " + e.getFile());
} catch (IOException e) {
    System.err.println("Failed to read config: " + e.getMessage());
} catch (IllegalArgumentException e) { // also catches NumberFormatException
    System.err.println("Bad port value: " + e.getMessage());
} finally {
    System.out.println("Config load attempted");
}

Never swallow an exception with an empty ; if you cannot handle it, let it propagate or wrap it in a more meaningful one.

對本章有疑問嗎?
上一章Modules and Packages下一章Key Concepts
catch

try-with-resources

Anything that must be closed, such as files, sockets, or connections, belongs in a try-with-resources header. It is closed automatically when the block exits, even on an exception. Any AutoCloseable works, and multiple resources close in reverse order.

static long countErrors(Path log) throws IOException {
    try (BufferedReader reader = Files.newBufferedReader(log)) {
        return reader.lines()
                .filter(line -> line.contains("ERROR"))
                .count();
    } // reader.close() runs automatically
}

Custom exceptions

Domain-specific exceptions let callers tell failures apart. Extend Exception when callers must plan for the failure, RuntimeException otherwise, and accept a cause so wrapped stack traces are preserved.

public class OrderNotFoundException extends RuntimeException {
    public OrderNotFoundException(long orderId) {
        super("order not found: " + orderId);
    }

    public OrderNotFoundException(long orderId, Throwable cause) {
        super("order not found: " + orderId, cause);
    }
}

Testing with JUnit

JUnit is the standard testing framework for Java, and tests use the Jupiter API introduced with JUnit 5. With Maven, add junit-jupiter as a test-scoped dependency (the previous chapter shows Gradle); test classes go in the same package under src/test/java.

<dependency>
  <groupId>org.junit.jupiter</groupId>
  <artifactId>junit-jupiter</artifactId>
  <version>${junit.version}</version>
  <scope>test</scope>
</dependency>

Annotate test methods with @Test and verify results with the static methods in Assertions. assertThrows checks that an exception is thrown and hands it back, so you can inspect its message too.

package com.example.config;

import static org.junit.jupiter.api.Assertions.*;

import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;

class ConfigLoaderTest {
    @Test
    @DisplayName("a valid port is parsed to a number")
    void parsesValidPort() {
        assertEquals(8080, ConfigLoader.parsePort("8080"));
    }

    @Test
    void rejectsOutOfRangePort() {
        var e = assertThrows(IllegalArgumentException.class,
                () -> ConfigLoader.parsePort("70000"));
        assertTrue(e.getMessage().contains("70000"));
    }

    @ParameterizedTest
    @ValueSource(strings = {"0", "-1", "65536"})
    void rejectsInvalidPorts(String value) {
        assertThrows(IllegalArgumentException.class, () -> ConfigLoader.parsePort(value));
    }
}

Run the suite with mvn test or ./gradlew test. @ParameterizedTest repeats a check over many inputs, and IDEs can run or debug a single test from the editor.

Summary

  • Checked exceptions must be caught or declared; unchecked exceptions extend RuntimeException.
  • Open anything that needs closing in a try-with-resources statement.
  • Give custom exceptions a cause constructor so wrapped failures keep their history.
  • Verify behavior with JUnit Jupiter's @Test, assertEquals, and assertThrows, and run tests through your build tool.

0 則留言

熱門留言由新到舊

登入 · 登入後即可留言。