Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I throw an exception in Clojure?

I wish to throw an exception and have the following:

(throw "Some text") 

However it seems to be ignored.

like image 760
yazz.com Avatar asked Mar 28 '11 13:03

yazz.com


People also ask

How do you throw a specific exception?

Throwing an exception is as simple as using the "throw" statement. You then specify the Exception object you wish to throw. Every Exception includes a message which is a human-readable error description. It can often be related to problems with user input, server, backend, etc.

Which exception we can throw?

We can throw either checked or unchecked exception. The throw keyword is mainly used to throw custom exceptions.

Can we handle exception with throws?

The throws keyword can be useful for propagating exceptions in the call stack and allows exceptions to not necessarily be handled within the method that declares these exceptions. On the other hand, the throw keyword is used within a method body, or any block of code, and is used to explicitly throw a single exception.

Can we throw exception from controller?

Controller Based Exception HandlingYou can add extra ( @ExceptionHandler ) methods to any controller to specifically handle exceptions thrown by request handling ( @RequestMapping ) methods in the same controller.


1 Answers

You need to wrap your string in a Throwable:

(throw (Throwable. "Some text")) 

or

(throw (Exception. "Some text")) 

You can set up a try/catch/finally block as well:

(defn myDivision [x y]   (try     (/ x y)     (catch ArithmeticException e       (println "Exception message: " (.getMessage e)))     (finally        (println "Done.")))) 

REPL session:

user=> (myDivision 4 2) Done. 2 user=> (myDivision 4 0) Exception message:  Divide by zero Done. nil 
like image 143
dbyrne Avatar answered Sep 21 '22 08:09

dbyrne