You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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
+
importjava.io.File;
32
+
importjava.io.FileReader;
33
+
importjava.io.IOException;
34
+
35
+
publicclassCheckedExceptionExample {
36
+
publicstaticvoidmain(String[] args) {
37
+
try {
38
+
FileReader file =newFileReader("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.
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.
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
+
importjava.io.File;
26
+
importjava.io.FileReader;
27
+
importjava.io.IOException;
28
+
29
+
publicclassCheckedExceptionExample {
30
+
publicstaticvoidmain(String[] args) {
31
+
try {
32
+
FileReader file =newFileReader("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
+
publicclassUncheckedExceptionExample {
48
+
publicstaticvoidmain(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`).
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
+
publicclassTryCatchExample {
88
+
publicstaticvoidmain(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
+
publicclassMultipleCatchExample {
107
+
publicstaticvoidmain(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
+
publicclassFinallyExample {
141
+
publicstaticvoidmain(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.
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