Example of Java exception handling mechanism: of Java throws exceptions catches and asserts

  • 2020-04-01 03:19:18
  • OfStack

This is a small example of basic exception handling, including throwing, catching, asserting, and logging.

Java exception handling is managed through five keywords: try, catch, throw, throw, finally. The basic procedure is to wrap a try block around the monitored statement. If there is an exception in the try block, the exception will be thrown. Your code can catch the exception in the catch block and handle it. There are also exceptions generated as part of the system that are thrown automatically at Java runtime. You can also declare the method to throw an exception on the method with the throws keyword, and then throw the exception object from within the method.


package com.hongyuan.test;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
public class ExceptionHandleTest {

 static{
  //Enable assertions, which are then enabled by classes loaded by the system class loader.
  ClassLoader.getSystemClassLoader().setDefaultAssertionStatus(true);
 }
 public static void main(String[] args) {
  
  try {
   TryCatchTest.run(10, -1);
  } catch (IOException e) {
   e.printStackTrace();
  }
  System.out.println("====================================================");

  //The log
  LogerTest.run();

  System.out.println("====================================================");
  //assertions
  AssertTest.div(3,0);

 }
}

class AssertTest {

 public static double div(int b,int a){

  assert a!=0:" Did your elementary school teacher know you used it that way? ";

  return (double)b/a;
 }
}

class LogerTest {

 private static Logger logger=null;

 static{
  // To obtain The log Object and define The log level 
  logger=Logger.getLogger(LogerTest.class.getName());
  logger.setLevel(Level.ALL);
 }

 public static void run(){
  //Enter the method
  logger.entering(LogerTest.class.getName(), "run");
  //General information
  logger.info(" Come to seek my trouble again, this account I write down!! ");
  //warning
  logger.warning(" I'm too tired to do this job!! ");
  //serious
  logger.log(Level.SEVERE," I quit !!! ^O^");
  //Exit the method
  logger.exiting(LogerTest.class.getName(), "run");
 }
}

class TryCatchTest {

 public static void run(int x,int y) throws IOException {

  try{//Must be

   if(x<0||y<0){
    throw new IllegalArgumentException(" Speechless, this let me do!! ");
   }

  }catch(Exception e){//optional

   IOException e1=new IOException(" It's up to you !");
   e1.initCause(e.getCause());

   throw e1;
  }finally{//optional

   System.out.println(" Finally they live a happy life!! (after) ");
  }
 }
}


< img SRC = "border = 0 / / files.jb51.net/file_images/article/201405/20140501074323.jpg? 20144174556 ">


Related articles: