Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Android

วิธีพิมพ์ Exception Message ใน Android

การจัดการและแสดง Exception Message ใน Android

ตัวอย่างสาธิตการจับ Exception (Try-Catch) แล้วแสดงข้อความผ่าน TextView และพิมพ์ Stack Trace ใน Logcat

ขั้นตอนที่ 1: สร้างโปรเจกต์ใหม่

Android Studio → File → New Project

ขั้นตอนที่ 2: Layout XML (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">
    </TextView>

</LinearLayout>

ขั้นตอนที่ 3: โค้ด Java (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 {
            // สร้าง ArithmeticException (หารด้วยศูนย์)
            int a = 0;
            int b = 10;
            int result = b / a; // <-- โยน Exception
            System.out.println(result);
        } catch (Exception e) {
            // 1. แสดงข้อความสรุปใน TextView
            text.setText(e.toString()); // java.lang.ArithmeticException: divide by zero

            // 2. พิมพ์ Stack Trace เต็มใน Logcat (สำคัญสำหรับ Debug)
            e.printStackTrace();

            // 3. หรือใช้ Log.e พร้อม Exception object
            // Log.e("ExceptionDemo", "Error occurred", e);
        }
    }
}

การทดสอบ

รันแอป TextView จะแสดง: java.lang.ArithmeticException: divide by zero

ใน Logcat จะเห็น Stack Trace เต็ม:

W/System.err: java.lang.ArithmeticException: divide by zero
W/System.err:     at com.example.myapplication.MainActivity.onCreate(MainActivity.java:25)
W/System.err:     at android.app.Activity.performCreate(Activity.java:...)
...

วิธีพิมพ์ Exception Message ใน Android

วิธีดึงข้อมูล Exception แบบต่างๆ

เมธอดคืนค่าใช้เมื่อไหร่
e.toString()Class name + messageแสดง User/Log สรุป
e.getMessage()Message เท่านั้นข้อความเฉพาะเจาะจง
e.getLocalizedMessage()Message แปลภาษาInternationalization
e.printStackTrace()Print to System.errDebug ใน Logcat
Log.e(TAG, msg, e)Log พร้อม Stack TraceProduction logging

Best Practices การจัดการ Exception

  1. Catch specific exception: catch (ArithmeticException e) แทน catch (Exception e)
  2. Log ทุกครั้ง: อย่า catch แล้วว่างเปล่า (Empty catch block)
  3. User-friendly message: แสดงข้อความเข้าใจง่ายให้ User, Log รายละเอียดให้ Dev
  4. Crash reporting: ใช้ Firebase Crashlytics หรือ Sentry สำหรับ Production

ตัวอย่างปรับปรุงสำหรับ Production

try {
    int result = 10 / 0;
} catch (ArithmeticException e) {
    // Log สำหรับ Developer
    Log.e(TAG, "Division by zero error", e);
    // แสดงข้อความให้ User
    text.setText("ไม่สามารถคำนวณได้: กรุณาตรวจสอบข้อมูลนำเข้า");
    // ส่งไป Crashlytics (ถ้ามี)
    // FirebaseCrashlytics.getInstance().recordException(e);
}