Skip to content

Commit b856a61

Browse files
committed
exception-handling
1 parent 732361e commit b856a61

File tree

4 files changed

+600
-4
lines changed

4 files changed

+600
-4
lines changed

docs/java/exception-handling/checked-vs-unchecked-exceptions.md

Lines changed: 140 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,4 +5,143 @@ sidebar_label: Checked vs Unchecked Exceptions
55
sidebar_position: 2
66
tags: [java, exceptions, programming, checked-exceptions, unchecked-exceptions]
77
description: In this tutorial, you will learn about checked and unchecked exceptions in Java. We will learn about the differences between checked and unchecked exceptions, how to handle them, and when to use them in Java programs.
8-
---
8+
---
9+
10+
# Checked vs Unchecked Exceptions in Java
11+
12+
## Introduction
13+
14+
Exceptions in Java are categorized into two main types: checked exceptions and unchecked exceptions. Understanding the differences between these two types is crucial for effective exception handling in Java.
15+
16+
## Checked Exceptions
17+
18+
### Definition
19+
20+
Checked exceptions are exceptions that are checked at compile-time. This means that the compiler ensures that these exceptions are either caught or declared in the method signature using the `throws` keyword.
21+
22+
### Characteristics
23+
24+
- **Compile-time Checking**: The compiler enforces handling of these exceptions.
25+
- **Must be Caught or Declared**: Methods that can throw checked exceptions must either catch them or declare them using the `throws` keyword.
26+
- **Typically Used for Recoverable Conditions**: Checked exceptions are often used for conditions from which the program can recover, such as I/O errors, network errors, and file not found exceptions.
27+
28+
### Example
29+
30+
```java
31+
import java.io.File;
32+
import java.io.FileReader;
33+
import java.io.IOException;
34+
35+
public class CheckedExceptionExample {
36+
public static void main(String[] args) {
37+
try {
38+
FileReader file = new FileReader("file.txt");
39+
} catch (IOException e) {
40+
System.out.println("File not found or unable to read the file");
41+
}
42+
}
43+
}
44+
```
45+
46+
### Common Checked Exceptions
47+
48+
- `IOException`
49+
- `SQLException`
50+
- `FileNotFoundException`
51+
- `ClassNotFoundException`
52+
53+
## Unchecked Exceptions
54+
55+
### Definition
56+
57+
Unchecked exceptions are exceptions that are not checked at compile-time. These are subclasses of `RuntimeException`. The compiler does not enforce handling of these exceptions, meaning they do not need to be declared or caught.
58+
59+
### Characteristics
60+
61+
- **Runtime Checking**: These exceptions occur during the execution of the program.
62+
- **No Requirement to Catch or Declare**: Methods are not required to handle or declare these exceptions.
63+
- **Typically Used for Programming Errors**: Unchecked exceptions are often used to indicate programming errors, such as logic errors or improper use of an API.
64+
65+
### Example
66+
67+
```java
68+
public class UncheckedExceptionExample {
69+
public static void main(String[] args) {
70+
try {
71+
int result = 10 / 0;
72+
} catch (ArithmeticException e) {
73+
System.out.println("Cannot divide by zero");
74+
}
75+
}
76+
}
77+
```
78+
79+
### Common Unchecked Exceptions
80+
81+
- `NullPointerException`
82+
- `ArrayIndexOutOfBoundsException`
83+
- `ArithmeticException`
84+
- `IllegalArgumentException`
85+
86+
## Key Differences
87+
88+
| Feature | Checked Exceptions | Unchecked Exceptions |
89+
|-----------------------------|-----------------------------------------|---------------------------------------|
90+
| **Compile-time Checking** | Yes | No |
91+
| **Handling Requirement** | Must be caught or declared | No requirement to catch or declare |
92+
| **Inheritance** | Extends `Exception` | Extends `RuntimeException` |
93+
| **Typical Use** | For recoverable conditions (e.g., I/O) | For programming errors (e.g., null pointers) |
94+
95+
## When to Use
96+
97+
### Checked Exceptions
98+
99+
- Use checked exceptions when the client code should be aware of and recover from the exception.
100+
- Ideal for scenarios where the error is due to external factors (e.g., network issues, file handling).
101+
102+
### Unchecked Exceptions
103+
104+
- Use unchecked exceptions to indicate programming errors that can be avoided by the developer.
105+
- Ideal for scenarios where the error is due to a bug in the code (e.g., null pointer access, array out-of-bounds).
106+
107+
## Example Comparison
108+
109+
### Checked Exception Example
110+
111+
```java
112+
import java.io.BufferedReader;
113+
import java.io.FileReader;
114+
import java.io.IOException;
115+
116+
public class CheckedExceptionDemo {
117+
public static void main(String[] args) {
118+
try {
119+
BufferedReader reader = new BufferedReader(new FileReader("file.txt"));
120+
String line = reader.readLine();
121+
System.out.println(line);
122+
reader.close();
123+
} catch (IOException e) {
124+
System.out.println("An I/O error occurred: " + e.getMessage());
125+
}
126+
}
127+
}
128+
```
129+
130+
### Unchecked Exception Example
131+
132+
```java
133+
public class UncheckedExceptionDemo {
134+
public static void main(String[] args) {
135+
String str = null;
136+
try {
137+
System.out.println(str.length());
138+
} catch (NullPointerException e) {
139+
System.out.println("A null pointer exception occurred: " + e.getMessage());
140+
}
141+
}
142+
}
143+
```
144+
145+
## Conclusion
146+
147+
Understanding the distinction between checked and unchecked exceptions is essential for writing robust Java applications. Checked exceptions force you to handle potential error conditions at compile time, making your code more resilient to expected issues. Unchecked exceptions, on the other hand, highlight potential bugs in your code that should be fixed by the developer. Proper use of both types of exceptions can lead to cleaner, more maintainable code.

docs/java/exception-handling/exception-basics-and-try-catch.md

Lines changed: 183 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,4 +5,186 @@ sidebar_label: Exception Basics and Try-Catch
55
sidebar_position: 1
66
tags: [java, exceptions, programming, exception-handling, java exceptions]
77
description: In this tutorial, we will learn about exceptions in Java. We will learn about what exceptions are, why they are important, and how to handle exceptions using try-catch blocks in Java programs.
8-
---
8+
---
9+
10+
# Exceptions Basics and Try-Catch in Java
11+
12+
## Introduction
13+
14+
Exceptions are events that disrupt the normal flow of a program's execution. In Java, exceptions provide a way to handle errors or other exceptional conditions in a controlled manner. Java provides a robust exception handling mechanism to manage runtime errors, making it easier to debug and maintain code.
15+
16+
## Types of Exceptions
17+
18+
### Checked Exceptions
19+
20+
Checked exceptions are exceptions that are checked at compile-time. These exceptions must be either caught or declared in the method signature using the `throws` keyword.
21+
22+
#### Example
23+
24+
```java
25+
import java.io.File;
26+
import java.io.FileReader;
27+
import java.io.IOException;
28+
29+
public class CheckedExceptionExample {
30+
public static void main(String[] args) {
31+
try {
32+
FileReader file = new FileReader("file.txt");
33+
} catch (IOException e) {
34+
System.out.println("File not found or unable to read the file");
35+
}
36+
}
37+
}
38+
```
39+
40+
### Unchecked Exceptions
41+
42+
Unchecked exceptions are exceptions that are not checked at compile-time. These are subclasses of `RuntimeException`. They occur during the execution of the program and can be caught, but are not required to be declared in the method signature.
43+
44+
#### Example
45+
46+
```java
47+
public class UncheckedExceptionExample {
48+
public static void main(String[] args) {
49+
try {
50+
int result = 10 / 0;
51+
} catch (ArithmeticException e) {
52+
System.out.println("Cannot divide by zero");
53+
}
54+
}
55+
}
56+
```
57+
58+
### Errors
59+
60+
Errors are serious issues that a reasonable application should not try to catch. They are usually related to the environment in which the application is running (e.g., `OutOfMemoryError`).
61+
62+
## Exception Hierarchy
63+
64+
- `Throwable`
65+
- `Exception`
66+
- `RuntimeException`
67+
- Checked exceptions (e.g., `IOException`, `SQLException`)
68+
- `Error` (e.g., `OutOfMemoryError`, `StackOverflowError`)
69+
70+
## Try-Catch Block
71+
72+
### Syntax
73+
74+
The `try` block contains code that might throw an exception, and the `catch` block contains code to handle the exception.
75+
76+
```java
77+
try {
78+
// Code that may throw an exception
79+
} catch (ExceptionType e) {
80+
// Code to handle the exception
81+
}
82+
```
83+
84+
### Example
85+
86+
```java
87+
public class TryCatchExample {
88+
public static void main(String[] args) {
89+
try {
90+
int[] numbers = {1, 2, 3};
91+
System.out.println(numbers[5]); // This will throw ArrayIndexOutOfBoundsException
92+
} catch (ArrayIndexOutOfBoundsException e) {
93+
System.out.println("Array index is out of bounds");
94+
}
95+
}
96+
}
97+
```
98+
99+
## Multiple Catch Blocks
100+
101+
You can have multiple catch blocks to handle different types of exceptions.
102+
103+
### Example
104+
105+
```java
106+
public class MultipleCatchExample {
107+
public static void main(String[] args) {
108+
try {
109+
int[] numbers = {1, 2, 3};
110+
System.out.println(numbers[5]);
111+
int result = 10 / 0;
112+
} catch (ArrayIndexOutOfBoundsException e) {
113+
System.out.println("Array index is out of bounds");
114+
} catch (ArithmeticException e) {
115+
System.out.println("Cannot divide by zero");
116+
}
117+
}
118+
}
119+
```
120+
121+
## Finally Block
122+
123+
The `finally` block is used to execute important code such as closing resources, regardless of whether an exception is thrown or not.
124+
125+
### Syntax
126+
127+
```java
128+
try {
129+
// Code that may throw an exception
130+
} catch (ExceptionType e) {
131+
// Code to handle the exception
132+
} finally {
133+
// Code to be executed regardless of an exception
134+
}
135+
```
136+
137+
### Example
138+
139+
```java
140+
public class FinallyExample {
141+
public static void main(String[] args) {
142+
try {
143+
int result = 10 / 0;
144+
} catch (ArithmeticException e) {
145+
System.out.println("Cannot divide by zero");
146+
} finally {
147+
System.out.println("This is the finally block");
148+
}
149+
}
150+
}
151+
```
152+
153+
## Try-With-Resources
154+
155+
The try-with-resources statement is a try statement that declares one or more resources. A resource is an object that must be closed after the program is finished with it. The try-with-resources statement ensures that each resource is closed at the end of the statement.
156+
157+
### Syntax
158+
159+
```java
160+
try (ResourceType resource = new ResourceType()) {
161+
// Use the resource
162+
} catch (ExceptionType e) {
163+
// Code to handle the exception
164+
}
165+
```
166+
167+
### Example
168+
169+
```java
170+
import java.io.BufferedReader;
171+
import java.io.FileReader;
172+
import java.io.IOException;
173+
174+
public class TryWithResourcesExample {
175+
public static void main(String[] args) {
176+
try (BufferedReader br = new BufferedReader(new FileReader("file.txt"))) {
177+
String line;
178+
while ((line = br.readLine()) != null) {
179+
System.out.println(line);
180+
}
181+
} catch (IOException e) {
182+
System.out.println("File not found or unable to read the file");
183+
}
184+
}
185+
}
186+
```
187+
188+
## Conclusion
189+
190+
Understanding exceptions and how to handle them is crucial for writing robust and maintainable Java code. Using try-catch blocks appropriately allows you to manage runtime errors gracefully and ensure your program can handle unexpected conditions without crashing.

0 commit comments

Comments
 (0)