-

1. 空指针异常(NullPointerException)

问题描述:在Kotlin中,尽管有空安全机制,但在使用可空类型时未进行空检查,仍可能导致空指针异常。

示例代码

1
2
val name: String? = null
println(name.length) // 会导致NullPointerException

解决方法

1
2
val name: String? = null
println(name?.length) // 使用安全调用操作符

2. 类型转换异常(ClassCastException)

问题描述:在类型转换时,如果对象不是目标类型,会抛出ClassCastException。

示例代码

1
2
val obj: Any = 123
val str: String = obj as String // 会导致ClassCastException

解决方法

1
2
val obj: Any = 123
val str: String? = obj as? String // 使用安全类型转换

3. 数组越界异常(ArrayIndexOutOfBoundsException)

问题描述:访问数组时,如果索引超出数组范围,会抛出ArrayIndexOutOfBoundsException。

示例代码

1
2
val arr = arrayOf(1, 2, 3)
println(arr[3]) // 会导致ArrayIndexOutOfBoundsException

解决方法

1
2
3
4
val arr = arrayOf(1, 2, 3)
if (arr.size > 3) {
println(arr[3])
}

4. 并发修改异常(ConcurrentModificationException)

问题描述:在遍历集合时修改集合内容,会抛出ConcurrentModificationException。

示例代码

1
2
3
4
5
6
val list = mutableListOf(1, 2, 3)
for (item in list) {
if (item == 2) {
list.remove(item) // 会导致ConcurrentModificationException
}
}

解决方法

1
2
3
4
5
6
7
8
val list = mutableListOf(1, 2, 3)
val iterator = list.iterator()
while (iterator.hasNext()) {
val item = iterator.next()
if (item == 2) {
iterator.remove()
}
}

5. 空集合操作异常(NoSuchElementException)

问题描述:在空集合上调用first()或last()等方法,会抛出NoSuchElementException。

示例代码

1
2
val list = emptyList<Int>()
println(list.first()) // 会导致NoSuchElementException

解决方法

1
2
val list = emptyList<Int>()
println(list.firstOrNull()) // 使用firstOrNull()方法

6. 协程取消异常(CancellationException)

问题描述:在协程被取消时,未正确处理取消操作,会抛出CancellationException。

示例代码

1
2
3
4
5
6
suspend fun longRunningTask() {
for (i in 1..1000) {
heavyComputation()
delay(100)
}
}

解决方法

1
2
3
4
5
6
7
suspend fun longRunningTask() {
for (i in 1..1000) {
ensureActive() // 检查协程是否活跃
heavyComputation()
delay(100)
}
}

7. 线程安全问题(Race Condition)

问题描述:在多线程环境下,未正确同步共享资源,可能导致数据不一致或崩溃。

示例代码

1
2
3
4
5
var counter = 0

fun increment() {
counter++
}

解决方法

1
2
3
4
5
val counter = AtomicInteger(0)

fun increment() {
counter.incrementAndGet()
}

8. 资源泄漏(Resource Leak)

问题描述:未正确关闭资源(如文件、数据库连接等),可能导致资源泄漏。

示例代码

1
2
3
4
fun readFile(path: String): String {
val reader = BufferedReader(FileReader(path))
return reader.readText()
}

解决方法

1
2
3
4
5
fun readFile(path: String): String {
return BufferedReader(FileReader(path)).use { reader ->
reader.readText()
}
}

9. 死锁(Deadlock)

问题描述:在多线程环境下,两个或多个线程相互等待对方释放锁,导致程序无法继续执行。

示例代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
val lock1 = Any()
val lock2 = Any()

fun thread1() {
synchronized(lock1) {
synchronized(lock2) {
// 操作
}
}
}

fun thread2() {
synchronized(lock2) {
synchronized(lock1) {
// 操作
}
}
}

解决方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
val lock1 = Any()
val lock2 = Any()

fun thread1() {
synchronized(lock1) {
synchronized(lock2) {
// 操作
}
}
}

fun thread2() {
synchronized(lock1) {
synchronized(lock2) {
// 操作
}
}
}

10. 内存泄漏(Memory Leak)

问题描述:未正确释放不再使用的对象引用,导致内存无法被回收。

示例代码

1
2
3
4
5
6
7
8
class MyActivity : Activity() {
private val listener = MyListener()

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
registerListener(listener)
}
}

解决方法

1
2
3
4
5
6
7
8
9
10
11
12
13
class MyActivity : Activity() {
private val listener = MyListener()

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
registerListener(listener)
}

override fun onDestroy() {
super.onDestroy()
unregisterListener(listener)
}
}

11. 栈溢出(StackOverflowError)

问题描述:递归调用过深,导致栈空间耗尽。

示例代码

1
2
3
fun recursiveFunction() {
recursiveFunction()
}

解决方法

1
2
3
4
5
6
fun recursiveFunction() {
if (/* 终止条件 */) {
return
}
recursiveFunction()
}

12. 未捕获异常(Uncaught Exception)

问题描述:未捕获的异常导致程序崩溃。

示例代码

1
2
3
fun main() {
throw RuntimeException("Uncaught exception")
}

解决方法

1
2
3
4
5
6
7
fun main() {
try {
throw RuntimeException("Uncaught exception")
} catch (e: Exception) {
println("Caught exception: $e")
}
}

13. 协程未处理异常(Unhandled Coroutine Exception)

问题描述:在协程中未处理异常,导致协程崩溃。

示例代码

1
2
3
4
5
fun main() = runBlocking {
launch {
throw RuntimeException("Unhandled exception")
}
}

解决方法

1
2
3
4
5
6
7
8
9
fun main() = runBlocking {
launch {
try {
throw RuntimeException("Unhandled exception")
} catch (e: Exception) {
println("Caught exception: $e")
}
}
}

14. 集合操作异常(IllegalStateException)

问题描述:在集合操作中,未正确处理状态,导致IllegalStateException。

示例代码

1
2
3
val list = mutableListOf(1, 2, 3)
val iterator = list.iterator()
iterator.remove() // 会导致IllegalStateException

解决方法

1
2
3
4
5
6
val list = mutableListOf(1, 2, 3)
val iterator = list.iterator()
if (iterator.hasNext()) {
iterator.next()
iterator.remove()
}

15. 异步任务未取消(Uncancelled Async Task)

问题描述:在Activity或Fragment销毁时,未取消异步任务,可能导致内存泄漏或崩溃。

示例代码

1
2
3
4
5
6
7
8
9
10
class MyActivity : Activity() {
private val job = Job()

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
GlobalScope.launch(job) {
// 长时间运行的任务
}
}
}

解决方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class MyActivity : Activity() {
private val job = Job()

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
GlobalScope.launch(job) {
// 长时间运行的任务
}
}

override fun onDestroy() {
super.onDestroy()
job.cancel()
}
}

16. 视图操作异常(IllegalStateException)

问题描述:在视图未准备好时进行操作,可能导致IllegalStateException。

示例代码

1
2
3
4
5
6
7
8
class MyFragment : Fragment() {
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
view.post {
// 视图操作
}
}
}

解决方法

1
2
3
4
5
6
7
8
9
10
class MyFragment : Fragment() {
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
if (isAdded && !isDetached) {
view.post {
// 视图操作
}
}
}
}

17. 数据库操作异常(SQLiteException)

问题描述:在数据库操作中,未正确处理异常,可能导致SQLiteException。

示例代码

1
2
3
fun insertData(db: SQLiteDatabase, data: String) {
db.execSQL("INSERT INTO table (column) VALUES ('$data')")
}

解决方法

1
2
3
4
5
6
7
fun insertData(db: SQLiteDatabase, data: String) {
try {
db.execSQL("INSERT INTO table (column) VALUES ('$data')")
} catch (e: SQLiteException) {
println("Database error: $e")
}
}

18. 网络请求异常(IOException)

问题描述:在网络请求中,未正确处理异常,可能导致IOException。

示例代码

1
2
3
fun fetchData(url: String): String {
return URL(url).readText()
}

解决方法

1
2
3
4
5
6
7
8
fun fetchData(url: String): String? {
return try {
URL(url).readText()
} catch (e: IOException) {
println("Network error: $e")
null
}
}

19. 文件操作异常(FileNotFoundException)

问题描述:在文件操作中,未正确处理异常,可能导致FileNotFoundException。

示例代码

1
2
3
fun readFile(path: String): String {
return File(path).readText()
}

解决方法

1
2
3
4
5
6
7
8
fun readFile(path: String): String? {
return try {
File(path).readText()
} catch (e: FileNotFoundException) {
println("File not found: $e")
null
}
}

20. 权限未授予(SecurityException)

问题描述:在未授予权限的情况下访问敏感资源,可能导致SecurityException。

示例代码

1
2
3
4
fun readContacts(context: Context): List<Contact> {
val cursor = context.contentResolver.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null)
return cursor?.use { /* 解析联系人 */ } ?: emptyList()
}

解决方法

1
2
3
4
5
6
7
8
fun readContacts(context: Context): List<Contact> {
return if (ContextCompat.checkSelfPermission(context, Manifest.permission.READ_CONTACTS) == PackageManager.PERMISSION_GRANTED) {
val cursor = context.contentResolver.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null)
cursor?.use { /* 解析联系人 */ } ?: emptyList()
} else {
emptyList()
}
}

21. 序列化异常(SerializationException)

问题描述:在序列化或反序列化对象时,未正确处理异常,可能导致SerializationException。

示例代码

1
2
3
fun serialize(obj: Any): ByteArray {
return ObjectOutputStream(ByteArrayOutputStream()).use { it.writeObject(obj) }.toByteArray()
}

解决方法

1
2
3
4
5
6
7
8
fun serialize(obj: Any): ByteArray? {
return try {
ObjectOutputStream(ByteArrayOutputStream()).use { it.writeObject(obj) }.toByteArray()
} catch (e: SerializationException) {
println("Serialization error: $e")
null
}
}

22. 反序列化异常(DeserializationException)

问题描述:在反序列化对象时,未正确处理异常,可能导致DeserializationException。

示例代码

1
2
3
fun deserialize(bytes: ByteArray): Any {
return ObjectInputStream(ByteArrayInputStream(bytes)).readObject()
}

解决方法

1
2
3
4
5
6
7
8
fun deserialize(bytes: ByteArray): Any? {
return try {
ObjectInputStream(ByteArrayInputStream(bytes)).readObject()
} catch (e: DeserializationException) {
println("Deserialization error: $e")
null
}
}

23. 视图未绑定(ViewNotBoundException)

问题描述:在视图未绑定时进行操作,可能导致ViewNotBoundException。

示例代码

1
2
3
4
5
6
7
8
class MyFragment : Fragment() {
private lateinit var textView: TextView

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
textView.text = "Hello"
}
}

解决方法

1
2
3
4
5
6
7
8
9
class MyFragment : Fragment() {
private lateinit var textView: TextView

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
textView = view.findViewById(R.id.textView)
textView.text = "Hello"
}
}

24. 资源未找到(NotFoundException)

问题描述:在访问未找到的资源时,可能导致NotFoundException。

示例代码

1
val drawable = resources.getDrawable(R.drawable.non_existent_drawable)

解决方法

1
2
3
4
5
6
val drawable = try {
resources.getDrawable(R.drawable.non_existent_drawable)
} catch (e: NotFoundException) {
println("Resource not found: $e")
null
}

25. 未处理的广播接收器(Unhandled BroadcastReceiver)

问题描述:在未正确处理广播接收器时,可能导致未处理的异常。

示例代码

1
2
3
4
5
class MyReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
// 处理广播
}
}

解决方法

1
2
3
4
5
6
7
8
9
class MyReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
try {
// 处理广播
} catch (e: Exception) {
println("Broadcast error: $e")
}
}
}

这些是Kotlin开发中常见的导致崩溃的问题及其解决方法。通过正确处理这些异常和潜在问题,可以显著提高应用的稳定性和用户体验。