java.lang.ArithmeticException জাভাতে একটি অনচেকড এক্সেপশন। সাধারণত java.lang.ArithmeticException: / by zero দেখা যায়, যা ঘটে যখন দুটি সংখ্যা ভাগ করার চেষ্টা করা হয় এবং হর (denominator) শূন্য হয়। ArithmeticException অবজেক্টগুলো JVM দ্বারা কনস্ট্রাক্ট করা হতে পারে।
উদাহরণ ১
public class ArithmeticExceptionTest {
public static void main(String[] args) {
int a = 0, b = 10;
int c = b/a;
System.out.println("Value of c is : "+ c);
}
}
উপরোক্ত উদাহরণে, হরের মান শূন্য হওয়ায় ArithmeticException ঘটেছে।
- java.lang.ArithmeticException: ভাগ করার সময় জাভা দ্বারা নিক্ষেপিত এক্সেপশন।
- / by zero: ArithmeticException অবজেক্ট তৈরি করার সময় দেওয়া ডিটেইল মেসেজ।
আউটপুট
Exception in thread "main" java.lang.ArithmeticException: / by zero
at ArithmeticExceptionTest.main(ArithmeticExceptionTest.java:5)
ArithmeticException কীভাবে হ্যান্ডেল করবেন
ArithmeticException কে try এবং catch ব্লক ব্যবহার করে হ্যান্ডেল করা যায়।
- যে স্টেটমেন্টগুলো ArithmeticException নিক্ষেপ করতে পারে সেগুলো try এবং catch ব্লক দিয়ে ঘেরে দিন।
- ArithmeticException ক্যাচ করুন।
- প্রোগ্রামের জন্য প্রয়োজনীয় অ্যাকশন নিন, কারণ এক্সিকিউশন অ্যাবোর্ট হবে না।
উদাহরণ ২
public class ArithmeticExceptionTest {
public static void main(String[] args) {
int a = 0, b = 10;
int c = 0;
try {
c = b/a;
} catch (ArithmeticException e) {
e.printStackTrace();
System.out.println("We are just printing the stack trace.\n" + "ArithmeticException is handled. But take care of the variable \"c\"");
}
System.out.println("Value of c :"+ c);
}
}
যখন একটি এक्सেপশন ঘটে, এক্সিকিউশন throw পয়েন্ট থেকে catch ব্লকে চলে যায়। এতে catch ব্লকের স্টেটমেন্ট এক্সিকিউট হয় এবং try-catch ব্লকের পরের স্টেটমেন্টগুলো চালিয়ে যায়।
আউটপুট
We are just printing the stack trace. ArithmeticException is handled. But take care of the variable "c"
Value of c is : 0
java.lang.ArithmeticException: / by zero
at ArithmeticExceptionTest.main(ArithmeticExceptionTest.java:6)