Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Android

Cách in thông báo ngoại lệ (Exception) trong Android

Xử lý và in Exception Message trong Android

Ví dụ này minh họa cách bắt ngoại lệ (try-catch), in thông báo lỗi ra TextView và ghi stack trace ra Logcat.

Bước 1: Tạo dự án mới

Android Studio → File → New Project.

Bước 2: Giao diện (res/layout/activity_main.xml)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center_horizontal"
    android:layout_marginTop="100dp"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/text"
        android:gravity="center"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>

Bước 3: Code logic (src/MainActivity.java)

package com.example.myapplication;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    TextView text;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        text = findViewById(R.id.text);

        try {
            int a = 0;
            int b = 10;
            int result = b / a; // Gây ArithmeticException: divide by zero
            System.out.println(result);
        } catch (Exception e) {
            // 1. Hiển thị thông báo lỗi ngắn gọn lên UI
            text.setText("Lỗi: " + e.toString());
            // Kết quả: "Lỗi: java.lang.ArithmeticException: divide by zero"

            // 2. In stack trace chi tiết ra Logcat (QUAN TRỌNG cho debug)
            e.printStackTrace();
        }
    }
}

Các phương thức hữu ích của Exception

e.getMessage()        // Chỉ thông báo: "divide by zero"
e.toString()          // Tên class + message: "java.lang.ArithmeticException: divide by zero"
e.getLocalizedMessage() // Message đã bản địa hóa
e.printStackTrace()   // In đầy đủ stack trace ra System.err (Logcat)
e.getStackTrace()     // Trả về mảng StackTraceElement để xử lý tùy chỉnh

Best Practice xử lý Exception trong Android

  • Luôn gọi e.printStackTrace() trong catch block khi debug.
  • Dùng Log.e("Tag", "Message", e) để log kèm throwable.
  • Tránh catch Exception chung chung, hãy catch cụ thể (ArithmeticException, NullPointerException, ...).
  • Không để catch block rỗng (empty catch block).

Chạy ứng dụng

TextView hiển thị: Lỗi: java.lang.ArithmeticException: divide by zero. Logcat hiển thị stack trace đầy đủ.

Cách in thông báo ngoại lệ (Exception) trong Android