Zum Hauptinhalt springen
ProdukteDesktop-WerkzeugeTASTECADZeichnungsprüfungTASTEFILESDateiverwaltungTASTEFTPDateiübertragungTASTESSHRemote-ArbeitsbereichTASTEZIPKomprimieren und EntpackenEntwicklerwerkzeugeTASTECODEIntegrierte Entwicklungsumgebung für RustTASTESTUDIOIntegrierte Entwicklungs- und TestumgebungTASTEETLDatenintegration (ETL)ServerTASTEREMOTERemote-Desktop-ServerTASTEGEOGeodatenserverTASTEMAILE-Mail-ArbeitsbereichErste SchritteDownloadsDokumentationKaufenAlle Produkte
Marktplatz
Neuigkeiten
TechnikNeuigkeitenEntwickler-News von heuteEntwicklerdokuProgrammiersprachenRustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDartWeb-Frontend-FrameworksNext.jsReactVue.js · NuxtSvelteKitAngularServer-FrameworksSpring BootDjangoFastAPIASP.NET CoreNestJS · ExpressApp- & Desktop-FrameworksTauriFlutterReact NativeElectronAlgorithmenAlgorithmus-GrundlagenKernalgorithmenFortgeschrittene AlgorithmenAlgorithmen für die Praxis
CommunityProjekteEntwicklungslogsPromptsProbleme mit KI-ToolsShowcaseCommunity-Leitfaden
ZusammenarbeitWissenstransferWebsite-AufbauDesktop-App-AufbauRelease- und ZahlungspipelineVertriebspartnerKontakt
DiensteRemote-DesktopIndividuelle Installationspakete
TASTEDEV
Produkte

Desktop-Werkzeuge

TASTECADKomplexe Zeichnungen, mühelos geöffnetTASTEFILESNur die Dateien, die zählen – in BestzeitTASTEFTPDer aufgeräumteste Weg für Ihre DateienTASTESSHDie stärkere Verbindung zu Ihren ServernTASTEZIPSchneller packen, sicherer entpacken

Entwicklerwerkzeuge

TASTECODERust-Apps bearbeiten, bauen, debuggen und testen – alles in einem FensterTASTESTUDIOVom Bearbeiten bis zu Remote-Tests und freigegebenen KI-KorrekturenTASTEETLDaten bewegen, die Werte im Blick

Server

TASTEREMOTEEin Remote-Desktop auf Ihrem eigenen ServerTASTEGEOEin GeoServer-kompatibler Geodatenserver, neu aufgebaut in RustTASTEMAILIhre E-Mail wieder in Ihrer Hand

Erste Schritte

DownloadsNeueste Versionen aller ProdukteDokuSo nutzen Sie jedes ProduktKaufenAbos und DauerlizenzenAlle ProdukteAlle Produkte im Überblick
Alle Produkte
MarktplatzNeuigkeiten
Technik

Neuigkeiten

Entwickler-News von heuteOffizielle Meldungen zu Sprachen, Frameworks, GitHub und KIEntwicklerdokuAnleitungen zu Sprachen, Frameworks und Algorithmen

Programmiersprachen

RustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDart

Frameworks

Web-Frontend-FrameworksNext.jsReactVue.js · NuxtSvelteKitAngular
Server-FrameworksSpring BootDjangoFastAPIASP.NET CoreNestJS · Express
App- & Desktop-FrameworksTauriFlutterReact NativeElectron

Algorithmen

Algorithmus-GrundlagenKomplexitätsanalyse · Sortieren · Suchen · Grundlegende Datenstrukturen · Bäume und HeapsKernalgorithmenGraphtraversierung · Kürzeste Wege und minimale Spannbäume · Dynamische Programmierung · Greedy-Algorithmen · Teile und herrsche · BacktrackingFortgeschrittene AlgorithmenZeichenkettenalgorithmen · Mathematik und Zahlentheorie · Bitmanipulation · Segmentbäume · Union-FindAlgorithmen für die PraxisStrategie für Coding-Interviews · LRU-Cache · Rate Limiting · Konsistentes Hashing
Alle Entwicklungsdokumente
Community
ProjekteEntwickler und Projekte entdeckenEntwicklungslogsEntscheidungen und ErkenntnissePromptsWiederverwendbare AnweisungenProbleme mit KI-ToolsProbleme und Workarounds für Claude, Codex, GeminiShowcaseFertige ErgebnisseCommunity-LeitfadenWie wir offen entwickeln
Zusammenarbeit
WissenstransferNative Apps mit Rust und eguiWebsite-Aufbau10 Sprachen, Konten, Dokumentation und DownloadsDesktop-App-AufbauRust und egui, ohne WebViewRelease- und ZahlungspipelineSignatur, MSI, deb, rpm, AppImage, PrüfsummenVertriebspartnerEmpfehlen und 30 % erhaltenKontaktEntwicklung, Partnerschaft, Investition
Dienste
Remote-DesktopIhren Computer im Browser erreichenIndividuelle InstallationspaketeNur nötige Funktionen, Einstellungen vorab
Kaufen
DE
한국어EnglishDeutschEspañolFrançaisItalianoPortuguês (Brasil)日本語简体中文繁體中文
Anmelden
Anmelden
TASTEDEV

Von kleinen Werkzeugen zu besserer Entwicklung.

support@tastedev.netTASTEDEV unterstützen
ProdukteProduktübersichtKaufenDokuDownloadsMarktplatzSupport
CommunityProjekteEntwicklungslogsPromptsProbleme mit KI-ToolsShowcase
RichtlinienDatenschutzerklärungNutzungsbedingungenAbo-BedingungenRückerstattungCommunity-Richtlinien
KontoAnmeldenRegistrieren
Besucher
Heute
012345678901234567890123456789012345678901234567890123456789
Gestern
012345678901234567890123456789012345678901234567890123456789
Aufrufe gesamt
0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
Firma
GXSOFT
Vertretungsberechtigt
CHOI YOUNG GU
Handelsregisternummer
853-44-00368
Anschrift
9F V24, 351 Gyeongin-ro, Michuhol-gu, Incheon, Republic of Korea
Telefon
+82-10-4404-1523
E-Mail
whitecalvin@tastedev.net
Datenschutzbeauftragter
CHOI YOUNG GU

© 2026 TASTEDEVProduktinformationen basieren auf verifizierten Entwicklungsquellen.Veröffentlicht · wird verbessert

Java-Dokumentation
Java
Getting StartedSyntax BasicsTypes and DataModules and PackagesErrors and TestingKey Concepts
Diskussionen

Java-Anleitung · 5/6

Errors and Testing

Dieses Kapitel ist vorerst nur auf Englisch verfügbar.

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.

Fragen zu diesem Kapitel?
Vorheriges KapitelModules and PackagesNächstes KapitelKey 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 Kommentare

Top-KommentareNeueste zuerst

Anmelden · Melde dich an, um einen Kommentar zu schreiben.