না, আমরা চেষ্টা, ধরা এবং অবশেষে ব্লক এর মধ্যে কোনো বিবৃতি লিখতে পারি না এবং এই ব্লকগুলি একটি ইউনিট গঠন করে। চেষ্টা এর কার্যকারিতা কীওয়ার্ড হল একটি ব্যতিক্রম বস্তুকে চিহ্নিত করা এবং সেই ব্যতিক্রম বস্তুটিকে ধরা এবং চিহ্নিত ব্যতিক্রম বস্তুর সাথে নিয়ন্ত্রণকে ক্যাচ ব্লক-এ স্থানান্তর করা। ব্লক চেষ্টা করুন এর কার্য সম্পাদন স্থগিত করে . ক্যাচ ব্লকের কার্যকারিতা ব্যতিক্রম ক্লাস অবজেক্টটি গ্রহণ করা যা ট্রাই দ্বারা পাঠানো হয়েছে এবং ধরা সেই ব্যতিক্রম ক্লাস অবজেক্ট এবং সেই ব্যতিক্রম ক্লাস অবজেক্টটিকে ক্যাচ -এ সংজ্ঞায়িত সংশ্লিষ্ট ব্যতিক্রম ক্লাসের রেফারেন্সে বরাদ্দ করে। ব্লক করুন . অবশেষে ব্লক করুন s ব্লক যা ব্যতিক্রম নির্বিশেষে বাধ্যতামূলকভাবে কার্যকর করা হবে।
আমরা বিবৃতি লিখতে পারি যেমন ক্যাচ ব্লক দিয়ে চেষ্টা করুন , একাধিক ক্যাচ ব্লক দিয়ে চেষ্টা করুন , অবশেষে ব্লক দিয়ে চেষ্টা করুন এবং ক্যাচ দিয়ে চেষ্টা করুন এবং অবশেষে ব্লক করুন এবং এই সমন্বয়গুলির মধ্যে কোন কোড বা বিবৃতি লিখতে পারে না। যদি আমরা এই ব্লকগুলির মধ্যে কোনও বিবৃতি দেওয়ার চেষ্টা করি, তাহলে এটি একটি কম্পাইল-টাইম ত্রুটি নিক্ষেপ করবে৷
সিনট্যাক্স
try { // Statements to be monitored for exceptions } // We can't keep any statements here catch(Exception ex){ // Catching the exceptions here } // We can't keep any statements here finally{ // finally block is optional and can only exist if try or try-catch block is there. // This block is always executed whether exception is occurred in the try block or not // and occurred exception is caught in the catch block or not. // finally block is not executed only for System.exit() and if any Error occurred. }
উদাহরণ
public class ExceptionHandlingTest { public static void main(String[] args) { System.out.println("We can keep any number of statements here"); try { int i = 10/0; // This statement throws ArithmeticException System.out.println("This statement will not be executed"); } //We can't keep statements here catch(ArithmeticException ex){ System.out.println("This block is executed immediately after an exception is thrown"); } //We can't keep statements here finally { System.out.println("This block is always executed"); } System.out.println("We can keep any number of statements here"); } }
আউটপুট
We can keep any number of statements here This block is executed immediately after an exception is thrown This block is always executed We can keep any number of statements here